JAVA執行緒wait()[等待]與notify()[喚醒]範例

class Cookies
{
   private int cookiesNo;
   private boolean empty = true;
   public synchronized void put (int cNo){
      while(!empty){
         try{
            wait(); //若盤子不是空的,則主人進入等待狀態
         } catch (InterruptedException e){}
      }
      System.out.println("主人放了第 " + cNo + " 塊餅乾.");
      cookiesNo = cNo;
      empty = false//盤子不是空的,意味著盤子內有餅乾可以吃了
      notify();      //呼叫小白狗來吃
   }
   public synchronized void eat(int cNo){
      while(empty){
         try{
            wait(); //若盤是空的,則小白進入等待狀態
         } catch (InterruptedException e){}
      }
      System.out.println("小白吃了第 " + cNo + " 塊餅乾.");
      empty = true;  //盤子是空的,意味著盤子內沒有餅乾了
      notify();      //呼叫主人來放餅乾
   }
}

class Eat implements Runnable
{  
   Cookies cookies;
   Eat(Cookies cookies){
      this.cookies = cookies;
   }
   public void run(){
      for(int i=1;i<=10;i++){
         cookies.eat(i);
      }
   }
}

class Put implements Runnable
{  
   Cookies cookies;
   Put(Cookies cookies){
      this.cookies = cookies;
   }
   public void run(){
      for(int i=1;i<=10;i++){
         cookies.put(i);
      }
   }
}

public class Dog_and_Cookies
{
   public static void main(String[] args){
      Cookies cookies = new Cookies();
      Put put = new Put(cookies);
      Eat eat = new Eat(cookies);
      Thread dog = new Thread(eat);
      Thread master = new Thread(put);
      dog.start();
      master.start();
   }
}

來源:猛虎出閘雙劍合璧版