Multithreading allows two parts of the same program to run concurrently. This article discusses how to pull off this performance-improving feat in Java. It is excerpted from chapter 10 of the book Java Demystified, written by Jim Keogh (McGraw-Hill/Osborne, 2004; ISBN: 0072254548).
Multithreading in Java - Using isAlive() and join() (Page 6 of 10 )
Typically, the main thread is the last thread to finish in a program. However, there isn’t any guarantee that the main thread won’t finish before a child thread finishes. In the previous example, we told the main method to sleep until the child threads terminate. However, we estimated the time it takes for the child threads to complete processing. If our estimate was too short, a child thread could terminate after the main thread terminates. Therefore, the sleep technique isn’t the best one to use to guarantee that the main thread terminates last.
Programmers use two other techniques to ensure that the main thread is the last thread to terminate. These techniques involve calling the isAlive() method and the join() method. Both of these methods are defined in the Thread class.
The isAlive() method determines whether a thread is still running. If it is, the isAlive() method returns a Boolean true value; otherwise, a Boolean false is returned. You can use the isAlive() method to examine whether a child thread continues to run. The join() method works differently than the isAlive() method. The join() method waits until the child thread terminates and “joins” the main thread. In addition, you can use the join() method to specify the amount of time you want to wait for a child thread to terminate.
The following example illustrates how to use the isAlive() method and the join() method in your program. This example is nearly the same as the previous example. The difference lies in the main() method of the Demo class definition.
After the threads are declared using the constructor of the MyThread class, the isAlive() method is called for each thread. The value returned by the isAlive() method is then displayed on the screen. Next, the join() method is called for each thread. The join() method causes the main thread to wait for all child threads to complete processing before the main thread terminates.
Here is what is displayed on the screen when this program runs: