Thread Joining
The isAlive() and looping technique is quite useful. In fact, that technique is the basis for Thread's three overloaded join() methods. A thread calls a join() method when it must wait for another thread to complete: The waiting thread is "joining" with a previously started thread (also known as a "forked" thread, by Unix aficionados). The no-argument join() method simply waits until another thread is no longer alive, which could be an indefinite period of time. That is why the other join() methods include a time-out provision: If a thread has not completed in the amount of time specified by the time-out, the waiting thread stops waiting.
NOTE
Because it is possible to interrupt a thread that is waiting to join with another thread, the join() methods are capable of throwing InterruptedException objects.
The transcendental number 2.71828..., represented by math symbol e, can be calculated by using the formula 1 / 0! + 1 / 1! + 1 / 2! + ... (where ! means factorial). Suppose we decide to create an application that performs that calculation in a new calculation thread. When the calculation thread completes, we would like the main thread to print the result. By calling join(), the main thread waits until the calculation completes before printing the result. The ThreadDemo5 application, whose source code appears in Listing 3, does just that.
Listing 3: ThreadDemo5.java.
// ThreadDemo5.java class ThreadDemo5 extends Thread { double e; public void run () { for (int i = 0; i < 20; i++) e += 1.0 / factorial (i); System.out.println ("Done"); } int factorial (int n) { if (n == 0) return 1; else return n * factorial (n - 1); } public static void main (String [] args) { ThreadDemo5 td5 = new ThreadDemo5 (); td5.start (); try { td5.join (); } catch (InterruptedException e) { } System.out.println ("e = " + td5.e); } }
ThreadDemo5 produces the following output:
Done e = 2.7182818351251554
NOTE
A thread can call the isAlive() and join() methods on itself. However, neither call makes any sense. If the current thread calls isAlive(), that method always returns true. If the current thread calls join(), the thread is attempting to join with itself. In other words, the current thread is waiting until it completes. You guessed it: The current thread waits forever! By the way, to obtain access to the current thread's Thread object, call Thread's currentThread() method.