What does this thread join code mean?
To quote from the Thread.join() method javadocs:
join()Waits for this thread to die.
There is a thread that is running your example code which is probably the main thread.
- The main thread creates and starts the
t1andt2threads. The two threads start running in parallel. - The main thread calls
t1.join()to wait for thet1thread to finish. - The
t1thread completes and thet1.join()method returns in the main thread. Note thatt1could already have finished before thejoin()call is made in which case thejoin()call will return immediately. - The main thread calls
t2.join()to wait for thet2thread to finish. - The
t2thread completes (or it might have completed before thet1thread did) and thet2.join()method returns in the main thread.
It is important to understand that the t1 and t2 threads have been running in parallel but the main thread that started them needs to wait for them to finish before it can continue. That’s a common pattern. Also, t1 and/or t2 could have finished before the main thread calls join() on them. If so then join() will not wait but will return immediately.
t1.join()means cause t2 to stop until t1 terminates?
No. The main thread that is calling t1.join() will stop running and wait for the t1 thread to finish. The t2 thread is running in parallel and is not affected by t1 or the t1.join() call at all.
In terms of the try/catch, the join() throws InterruptedException meaning that the main thread that is calling join() may itself be interrupted by another thread.
while (true) {
Having the joins in a while loop is a strange pattern. Typically you would do the first join and then the second join handling the InterruptedException appropriately in each case. No need to put them in a loop.