我对 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/