java - 如果在线程上调用 java wait(),该方法也会在 run() 方法终止时退出

标签 java multithreading

我对 wait() 方法的特定用例感到困惑。
根据javadoc,当发生以下情况之一时,等待应该结束:

  • 另一个线程调用notify或notifyAll(好吧,有关notify的详细信息请参阅javadoc,但这与本问题无关)
  • 另一个线程中断了这个(等待)线程
  • 超时到期(如果使用带超时的等待版本)

如果我正在等待的对象本身是一个线程,即使没有调用notify(),并且上述条件都不成立,wait()也会退出。 但当 Thread.run() 方法结束时就会发生这种情况。 虽然这种行为可能有意义,但它不应该记录在 Thread javadoc 中吗? 我发现它非常令人困惑,因为它与 join() 行为重叠。

这是我的测试代码:

public static class WorkerThread extends Thread {

    @Override public void run() {

        try{
           System.out.println("WT: waiting 4 seconds");
           Thread.sleep(4000);

           synchronized (this) {
            notify();
           }

           System.out.println("WT: waiting for 4 seconds again");
           Thread.sleep(4000);
           System.out.println("WT: exiting");

        } catch (InterruptedException ignore) {
            ignore.printStackTrace();
        }

    }

}

public static void main (String [] args) throws InterruptedException {

    WorkerThread w = new WorkerThread();

    w.start();

    synchronized(w) {
        w.wait();
        System.out.println("MT: The object has been notified by the thread!");
    }

    synchronized(w) {

        w.wait(); //THIS FINISHES WITHOUT notify(), interrupt() OR TIMEOUT!

        System.out.println("MT: The thread has been notified again!");
    }

}

最佳答案

自 Java 7 起就有记录,在 documentation of the join() method 中:

As a thread terminates the this.notifyAll method is invoked. It is recommended that applications not use wait, notify, or notifyAll on Thread instances.

关于java - 如果在线程上调用 java wait(),该方法也会在 run() 方法终止时退出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16887540/

相关文章:

java - 在java中将字节数组传递给fileinputstream的方法

java - 如何在另一台机器上运行java数据库程序?

java - 边框布局程序未按预期完成

c - Select() 在阻塞时无法通过 FD_SET 识别更改

java - 如何允许在线程中运行的两个对象在 Java 中进行通信?

java - 关闭标准输出后 : Java silently swallows everything written to stdout

java - Apache 公共(public) csv

c# - 使用 System.Net.Mail 加速通过 smtp 服务器发送多封电子邮件

c++ - 两个程序在本地循环中通信时互相阻塞

c# - 一种在子线程被杀死或中断时通知父线程的方法