我对wait()方法的特定用例感到困惑.
根据javadoc,当出现下列情况之一时,wait应该结束:
在我正在等待的对象本身就是一个Thread的情况下,即使没有调用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) { …Run Code Online (Sandbox Code Playgroud)