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

对象锁,是 使用一个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

你可能感兴趣的:(多线程)