The explanation of how thread termination sends a notifyAll notification is correct and correct, +1 from me. I will try to add some information on why this is relevant.
When you call
synchronized(t) { t.wait(10000);}
in the main thread, this is the main thread that performs the wait. t is the monitor that is waiting for the main thread. Your expectation that this will cause your thread t become inactive is wrong.
The monitor here (a shared object that is locked, which is t ) is used to communicate between different threads, the thread calls notifyAll on the monitor, and other threads waiting on the monitor receive a notification. You can consider the monitor as a common point of communication.
In the first example, thread t starts and ends immediately (because it has nothing to do). The thread ends and sends its notification before the main thread starts to wait, so you will see a delay before the timeout expires.
In the second example, stream t has something to print, between it and the main stream there is a race condition. It is free for everyone, what happens first of all depends on the randomness of time. What you see is that thread t should now print the line to the console, so it manages to stay busy long enough to keep it alive while the main thread starts to wait, allowing the main thread to receive a notification when t ends, forcing the main thread to reduce latency.
Nathan hughes
source share