when main thread exits from thread join method

I am reading java thread source code, there is a little problem I am not sure. there are two thread, main thread and work thread which is a long time consumed thread, I want main thread to wait until work thread dies, so I call join method on work thread, in Thread source code, main thread waits when work thread is alive:

 while (isAlive()) {
            wait(0);
        }

when work thread completes work and dies, so what happens to main thread now? does it notified by thread scheduler by calling notifyAll method on work thread automatically?

Answer

Since the joining thread has called wait() as you’ve seen in the source code, then the target thread must call notify() or notifyAll to wake it up.

If you can’t see that anywhere in the Thread source code, then it may happen in a different class, or the native code or the non-public JVM-vendor implementation code.

But that is an implementaion detail: you can be certain that join will return when the target thread finishes as described in the documentation.

Leave a Reply

Your email address will not be published. Required fields are marked *