请检查下面的代码,即使我没有调用notify(),它也能正常工作。 所以我的问题是任何线程在死亡之前都会隐式调用notifyAll()吗?
class ThreadB extends Thread{
int total;
@Override
public void run() {
super.run();
synchronized (this) {
for(int i=0; i<100; i++)
total += i;
}
}
}
public class ThreadA {
public static void main(String[] args) throws InterruptedException{
ThreadB b = new ThreadB();
b.start();
synchronized (b) {
b.wait();
System.out.println("ThreadA.main()");
}
}
}
最佳答案
是的。 javadoc州
As a thread terminates the
this.notifyAll
method is invoked. It is recommended that applications not usewait
,notify
, ornotifyAll
onThread
instances.
关于您的评论
as your comment it will call
notifyAll()
when it terminates but what happens if thread is terminated and after that we calledjoin()
method
Here's java.lang.Thread
的最新实现。它还检查 Thread#isAlive()
。当线程完成时,isAlive
将返回 false
。
场景如下:线程终止,其内部 isAlive
标志变为 false
,并对其调用 notifyAll
。另一个线程对其调用 join
并检查 isAlive
。由于它返回 false
,因此对 join
的调用会立即返回。
关于java - 在任何线程死亡之前,它都会为等待线程引用的所有对象调用notify,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26696986/