[英]Java wait notify - notify notifies all threads
我有两个扩展线程的类和一个等待/通知
class A extends Thread {
int r = 20;
public void run() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (this) {
notify();
}
}
}
class B extends Thread {
A a;
public B(A a) {
this.a = a;
}
public void run() {
synchronized (a) {
System.out.println("Starting...");
try {
a.wait();
} catch (InterruptedException e) {
}
System.out.println("Result is: " + a.r);
}
}
}
A类在执行结束时通知B类
A a = new A();
new B(a).start();
new B(a).start();
new B(a).start();
和下面的代码
a.start();
通知所有线程
new Thread(a).start();
通知一个线程
为什么a.start()通知所有线程?
不是
a.start();
通知所有线程。 实际上,由a
引用的线程终止会通知所有在其监视器上等待的线程。
这在javadoc中有解释
当线程终止时,将调用
this.notifyAll
方法。 建议应用程序不要在Thread
实例上使用wait
,notify
或notifyAll
。
另一方面,在
new Thread(a).start();
您将a
用作Runnable
而不是Thread
。 将调用this.notifyAll
的实际线程是由实例创建表达式new Thread(a)
创建的new Thread(a)
,没有其他线程调用此Object#wait()
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.