I'm puzzled with a particular use case of the wait() method.
According with javadoc, wait should end when one of the following condition happens:
- another thread invokes notify or notifyAll (ok, see javadoc for a detail on notify but this is not relevant for this question)
- another thread interrupts this (waiting) thread
- a timeout expires (if using the wait version with timeout)
In the case in which the object i'm waiting on is itself a Thread, it happens that the wait() exits even if no notify() has been called, and no one of the above conditions holds. But it happens when the Thread.run() method ends. While this behavior may make sense, shouldn't it be documented inside of Thread javadoc? I find it very confusing also because it overlaps with join() behavior.
This is my test code:
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!");
}
}