public class 等待唤醒 {
public static void main(String[] args) {
Object lock = new Object();
new Thread(new Runnable() {
@Override
public void run() {
try {
//等待顾客说要买什么东西
synchronized (lock){
lock.wait();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("收到,你想要油条*2是吧?...");
try {
Thread.sleep(2000);
System.out.println("2.正在做早餐...");
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (lock){
System.out.println("3.做好了,请享用....");
lock.notify();
}
}
},"老板").start();
new Thread(new Runnable() {
@Override
public void run() {
System.out.println("1.告诉老板我要吃什么");
synchronized (lock){
lock.notify();
}
try {
System.out.println("等待老板做好早餐");
synchronized (lock){
lock.wait();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
},"顾客").start();
}
}```
Java多线程wait()、notify() 线程通信的小demo
最新推荐文章于 2023-03-24 11:08:34 发布