如果线程的wait比notify先执行,那么程序就死了,怎么才能解决这个问题?
public class AaaTest {
public static void main(String[] args) throws InterruptedException {
Object obj=new Object();
Ttt ttt=new Ttt(obj);
ttt.start();
synchronized(obj){
obj.wait();
}
System.out.println("wait先执行,程序通过");
}
static class Ttt extends Thread{
Object obj;
Ttt(Object obj){
this.obj=obj;
}
public void run() {
synchronized(obj){
obj.notify();
}
}
}
}
这样是否能够100%保证 obj.wait(); 在 obj.notify(); 之前执行?
https://blog.csdn.net/huanyuminhao/article/details/51960256
把ttt.start();放在synchronized的后面不就行了,因为AaaTest先获得锁
不能够100%保证 绝大多数数情况下是main线程先获得锁 执行wait() 但是理论上讲Ttt 也是有可能先获取到锁的 要想100%保证 先让Ttt睡眠1毫秒
空间花括号