Answering just the question in your title:
Does a thread run this.notifyAll when its run method is over?
The documentation for Oracle's Java 12 edition says, Yes, the join()
method calls wait()
waiting for a notification that the thread has terminated.
But note! It also says, "It is recommended that applications not use wait, notify, or notifyAll on Thread instances." It also says, "...this implementation..." Some other Java Run-time Environment might implement thread.join()
in a different way, and a program that depends on a Thread
object to be notify()
ed when the thread terminates might not work if you run it on the other JRE.
Also, see @akuzminykh's answer. Summary:
The notify()
and notifyAll()
methods do not do anything at all unless some other thread already is waiting in a wait()
call. If your program terminates by itself, that's nice, but you should not depend on it to terminate by itself. By the time the main thread calls thread.wait()
there's no reason to expect that any other thread will call thread.notify()
, and so there's no reason to expect that the thread.wait()
won't wait forever.
I'm just curious about the mechanism of join
...
Take a look at the source code for the OpenJDK version of the Thread
class.
http://hg.openjdk.java.net/jdk10/jdk10/jdk/file/777356696811/src/java.base/share/classes/java/lang/Thread.java
The join()
method just calls join(0)
, and in the special case where the millis
argument to join(long millis)
is zero, all it does is this:
while (isAlive()) {
wait();
}
In other words, all it does is wait()
until the thread is not alive.
Note! You won't find the notify()
call in the Thread.java
source file. The notification happens somewhere else (maybe native code?) after the thread's run()
method either returns or throws an exception.