Wait/Notify实现生产者-消费者
作者:
Roc_8
,
2025-04-14 23:15:39
· 广东
,
所有人可见
,
阅读 1
public class WaitNotifyExample {
private static final Object lock = new Object();
public static void main(String[] args) {
Thread producer = new Thread(() -> {
synchronized (lock){
try {
System.out.println("Producer: Producing...");
Thread.sleep(2000);
System.out.println("Producer: Production finished. Notifying consumer.");
lock.notify();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
Thread consumer = new Thread(() -> {
synchronized (lock){
try {
System.out.println("Consumer: Waiting for production to finish.");
lock.wait();
System.out.println("Consumer: Production finished. Consuming...");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
consumer.start();
producer.start();
}
}