司機(消費者)等待乘客(生產者)上車,乘客上車後通知司機發車,司機開車到站後讓乘客下車,循環往複。共享物件 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 物件的實例鎖,雙方必須同步於同一物件。notify() 喚醒。while (!condition) wait())防止虛假喚醒。Java 5+ 推薦使用 java.util.concurrent 套件:BlockingQueue、Semaphore、Condition 等高層抽象,更安全、可讀性更高、功能更豐富。