java中为什么notify可能会导致死锁,而notifyAll则不会
packagecom.tyxh.block;
classOutTurn {
privatebooleanisSub=true;
privateintcount= 0;
publicsynchronizedvoidsub() {
try{
while(!isSub) {
this.wait();
}
System.out.println("sub ---- "+count);
isSub=false;
this.notify();
}catch(Exception e) {
e.printStackTrace();
}
count++;
}
publicsynchronizedvoidmain() {
try{
while(isSub) {
this.wait();
}
System.out.println("main (((((((((((( "+count);
isSub=true;
this.notify();
}catch(Exception e) {
e.printStackTrace();
}
count++;
}
}
|
packagecom.tyxh.block;
publicclassLockDemo {
publicstaticvoidmain(String[] args) {
// System.out.println("lock");
finalOutTurn ot =newOutTurn();
for(intj = 0; j < 100; j++) {
newThread(newRunnable() {
publicvoidrun() {
// try {
// Thread.sleep(10);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
for(inti = 0; i < 5; i++) {
ot.sub();
}
}
}).start();
newThread(newRunnable() {
publicvoidrun() {
// try {
// Thread.sleep(10);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
for(inti = 0; i < 5; i++) {
ot.main();
}
}
}).start();
}
}
}
|
notify()和notifyAll()都是Object对象用于通知处在等待该对象的线程的方法。
void notify(): 唤醒一个正在等待该对象的线程。