首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 程式設計入門

wait()/notify() 經典生產者-消費者模式實戰範例

     編輯:Java 程式設計入門

場景:汽車載客模擬

司機(消費者)等待乘客(生產者)上車,乘客上車後通知司機發車,司機開車到站後讓乘客下車,循環往複。共享物件 Car 作為同步監視器。

完整代碼

public class Road {
    public static void main(String[] args) {
        Car car = new Car();
        new Thread(new Driver(car)).start();
        new Thread(new Passenger(car)).start();
    }
}

class Car {
    synchronized public void waitForPassenger() {
        try { wait(); } catch (InterruptedException ignored) {}
    }
    synchronized public void notifyDriver() {
        notify();
    }
}

class Passenger implements Runnable {
    private final Car car;
    public Passenger(Car car) { this.car = car; }

    public void run() {
        while (true) {
            Thread.yield();
            try { Thread.sleep(3000); } catch (InterruptedException ignored) {}
            System.out.println("乘客上車");
            car.notifyDriver();
            System.out.println("等待發車...");
            car.waitForPassenger();
        }
    }
}

class Driver implements Runnable {
    private final Car car;
    public Driver(Car car) { this.car = car; }

    public void run() {
        while (true) {
            System.out.println("等待乘客...");
            car.waitForPassenger();
            try { Thread.sleep(3000); } catch (InterruptedException ignored) {}
            Thread.yield();
            try { Thread.sleep(100); } catch (InterruptedException ignored) {}
            car.notifyDriver();
            System.out.println("乘客下車,繼續等待下一位");
        }
    }
}

核心機制解析

  • 同步監視器:Car 物件的實例鎖,雙方必須同步於同一物件。
  • wait():釋放鎖並進入等待集合,直到 notify() 喚醒。
  • notify():喚醒該物件等待集合中任一線程(非指定)。
  • while(true) 迴圈:模擬持續服務,實務中常搭配條件變數判斷(如 while (!condition) wait())防止虛假喚醒。

現代替代方案

Java 5+ 推薦使用 java.util.concurrent 套件:BlockingQueue、Semaphore、Condition 等高層抽象,更安全、可讀性更高、功能更豐富。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved