1. 程式人生 > 實用技巧 >做買包子案例:等待喚醒wait

做買包子案例:等待喚醒wait

package com.chunzhi.Test10WaitAndNotify;
/*
    等待喚醒案例:執行緒之間的通訊
        建立一個顧客執行緒:告知老闆要的包子種類和數量,呼叫wait方法,放棄cpu執行權,進入到WAITING狀態(無限等待)
        建立一個老闆執行緒:花了5秒做包子,做好包子之後,呼叫notify方法,喚醒顧客吃包子
 */
public class Test01WaitAndNotify {
    public static void main(String[] args) {
        // 建立一個鎖物件
        Object obj = new
Object(); // 建立匿名顧客執行緒 new Thread() { @Override public void run() { while (true) { // 保證等待和喚醒的執行緒只能有一個執行,需要使用同步技術 synchronized (obj) { System.out.println("告知老闆包子的種類和數量");
// 進行執行緒等待,等待老闆做包子 try { obj.wait(); } catch (InterruptedException e) { e.printStackTrace(); } // 被notify方法喚醒後執行的程式碼 System.out.println("顧客開始吃包子"); System.out.println(
"------------------"); } } } }.start(); // 建立匿名老闆執行緒 new Thread() { @Override public void run() { while (true) { // 做包子需要3秒鐘 try { Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } // 保證等待和喚醒的執行緒只能有一個執行,需要使用同步技術 synchronized (obj) { System.out.println("老闆花了3秒做好了包子,可以開吃了"); // 包子做好後,使用notify方法喚醒顧客吃包子 obj.notify(); } } } }.start(); } }