notify 和 notifyAll 的区别
(一)先看一个 notify发生死锁的例子:
http://blog.csdn.net/tayanxunhua/article/details/20998449
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对象用于通知处在等待该对象的线程的方法。
public class WaitAndNotify {
public static void main(String[] args) {
Object co = new Object();
System.out.println(co);
for (int i = 0; i < 5; i++) {
MyThread t = new MyThread("Thread" + i, co);
t.start();
}
try {
TimeUnit.SECONDS.sleep(2);
System.out.println("-----Main Thread notify-----");
synchronized (co) {
co.notify();
}
TimeUnit.SECONDS.sleep(2);
System.out.println("Main Thread is end.");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
static class MyThread extends Thread {
private String name;
private Object co;
public MyThread(String name, Object o) {
this.name = name;
this.co = o;
}
@Override
public void run() {
System.out.println(name + " is waiting.");
try {
synchronized (co) {
co.wait();
}
System.out.println(name + " has been notified.");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
运行结果:
java.lang.Object@1540e19d
Thread1 is waiting.
Thread2 is waiting.
Thread0 is waiting.
Thread3 is waiting.
Thread4 is waiting.
-----Main Thread notify-----
Thread1 has been notified.
Main Thread is end.
将其中的那个notify换成notifyAll,运行结果:
Thread0 is waiting.
Thread1 is waiting.
Thread2 is waiting.
Thread3 is waiting.
Thread4 is waiting.
-----Main Thread notifyAll-----
Thread4 has been notified.
Thread2 has been notified.
Thread1 has been notified.
Thread3 has been notified.
Thread0 has been notified.
Main Thread is end.
运行环境jdk8,结论:
notify唤醒一个等待的线程;notifyAll唤醒所有等待的线程。
notify 与 nofityall,notify造成死锁实践
优质内容筛选与推荐>>