java - 在任何线程死亡之前,它都会为等待线程引用的所有对象调用notify

标签 java android

请检查下面的代码,即使我没有调用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 use wait, notify, or notifyAll on Thread instances.

关于您的评论

as your comment it will call notifyAll() when it terminates but what happens if thread is terminated and after that we called join() 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/

相关文章:

java - Android前台服务onStartCommand不调用,仅onCreate调用

Java InetAddress.getByName &/etc/主机

android - 如何在短信中添加发件人姓名

android - 为什么我的布局 OnItemClickListener 现在不工作?

java - Jenkins:失败的 TestNG 测试中的错误消息未格式化

java - 如何使用 RxJava 逐个读取字符串数组成员并调用网络 API 获取第一个结果?

java - 当我从列表中选择一个项目时,如何打开带有按钮的弹出窗口?-在 Android 应用程序中

java - 如何在 Spring Boot MVC Web 应用程序中从 META/MANIFEST.MF 读取数据?

Java 日期和标准格式

java - JQuery、AJAX、POST请求、参数丢失