public static void main(String[] args) {
Object obj = new Object();
new Thread(){
@Override
public void run() {
while (true){
synchronized (obj){
System.out.println("等待老板做包子");
System.out.println(Thread.currentThread().getName());
try {
obj.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("包子做好了");
System.out.println("_______________");
}
}
}
}.start();
new Thread(){
@Override
public void run() {
while (true){
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (obj){
System.out.println(Thread.currentThread().getName());
System.out.println("包子开始做了");
obj.notify();
}
}
}
}.start();
}
为什么总是wait()线程抢到cpu的执行权而不是notify()所在的线程?求解
本文通过一个具体的Java代码示例,深入探讨了线程间的wait()和notify()方法的执行机制,解释了为什么wait()线程总是在notify()线程之前获取CPU执行权的现象,帮助读者理解线程同步中的微妙之处。
3782

被折叠的 条评论
为什么被折叠?



