码迷,mamicode.com
首页 > 编程语言 > 详细

多线程-wait(针对OBJECT对象锁的方式)

时间:2016-05-06 12:34:40      阅读:133      评论:0      收藏:0      [点我收藏+]

标签:

对象锁,是 使用一个object 对象,将这个对象供多个线程共享使用,然后再线程中,对这个对象加锁。

直接看代码

package com.luoy.Thread.wait;

public class ObjectWait2{

   public static void main(String[] args)
         throws InterruptedException{

      Object b = new Object();
      Object c = new Object();

     new Thread(new BuyFood(b, c)).start();
     Thread.sleep(1000);
     new Thread(new CookFood(b, c)).start();
   }
}

class BuyFood
      implements
         Runnable{

   private Object block;

   private Object clock;

   public BuyFood(Object block,
               Object clock){
      this.block = block;
      this.clock = clock;
   }

   @Override
   public void run(){

      for(int i = 0; i < 10; i++){

         synchronized(clock){
            //得到买的锁
            synchronized(block){
               p("买萝卜"+i);
               block.notify();
            }
            try{
               clock.wait();
            }catch(InterruptedException e){
               // TODO Auto-generated catch block
               e.printStackTrace();
            }

         }

         try{
            Thread.sleep(1000);
         }catch(InterruptedException e){
            // TODO Auto-generated catch block
            e.printStackTrace();
         }
      }

   }

   private void p(String s){
      System.out.println(s);
   }

}



class CookFood
      implements
         Runnable{

   private Object block;

   private Object clock;

   public CookFood(Object block,
               Object clock){
      this.block = block;
      this.clock = clock;
   }

   @Override
   public void run(){

      for(int i = 0; i < 10; i++){

      synchronized(block){
         //得到买的锁
         synchronized(clock){
            p("煮萝卜"+i);
               clock.notify();
         }
            try{
               block.wait();
            }catch(InterruptedException e){
               // TODO Auto-generated catch block
               e.printStackTrace();
            }
      }
      }

   }

   private void p(String s){
      System.out.println(s);
   }

}

结果

买萝卜0
煮萝卜0
买萝卜1
煮萝卜1
买萝卜2
煮萝卜2
买萝卜3
煮萝卜3
买萝卜4
煮萝卜4
买萝卜5
煮萝卜5
买萝卜6
煮萝卜6
买萝卜7
煮萝卜7
买萝卜8
煮萝卜8
买萝卜9
煮萝卜9

多线程-wait(针对OBJECT对象锁的方式)

标签:

原文地址:http://blog.csdn.net/walle167/article/details/51328790

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!