Monday, July 21, 2014

What does this thread join code mean?

To quote from the Thread.join() method javadocs:
Waits for this thread to die.
So t1.join() is called to wait for the t1 thread to finish. Then t2.join() is called to wait for the t2thread to finish. The 2 threads have been running in parallel but the thread that started them (probably the main thread) needs to wait for them to finish before continuing. That's a common pattern. When the main thread calls t1.join() it will stop running and wait for the t1 thread to finish.
The break; really isn't necessary but is there because the code is in a while(true) loop. That's a very strange pattern and probably can be removed. join() does throw InterruptedException but that means that the thread that is calling join() was interrupted. In that case the main thread should not loop around.

No comments:

Post a Comment