package com.tyxh.block;
class OutTurn {
private boolean isSub = true;
private int count = 0;
public synchronized void sub() {
try {
while (!isSub ) {
this.wait();
}
System. out.println("sub ---- " + count);
isSub = false ;
this.notify();
} catch (Exception e) {
e.printStackTrace();
}
count++;
}
public synchronized void main() {
try {
while (isSub ) {
this.wait();
}
System. out.println("main (((((((((((( " + count);
isSub = true ;
this.notify();
} catch (Exception e) {
e.printStackTrace();
}
count++;
}
}
|
package com.tyxh.block;
public class LockDemo {
public static void main(String[] args) {
// System.out.println("lock");
final OutTurn ot = new OutTurn();
for (int j = 0; j < 100; j++) {
new Thread(new Runnable() {
public void run() {
// try {
// Thread.sleep(10);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
for (int i = 0; i < 5; i++) {
ot.sub();
}
}
}).start();
new Thread(new Runnable() {
public void run() {
// try {
// Thread.sleep(10);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
for (int i = 0; i < 5; i++) {
ot.main();
}
}
}).start();
}
}
}
|
notify()和notifyAll()都是Object对象用于通知处在等待该对象的线程的方法。
java中为什么notify()可能会导致死锁,而notifyAll()则不会
原文:https://www.cnblogs.com/YuyuanNo1/p/11549781.html