final void join () – The isAlive () method occasionally useful as continuously checking the value returned by this method and then sleeping makes a very inefficient use of the CPU time. So a better alternative to wait for a thread to die is to use join () method of the Thread class.
The join () method causes the current thread to wait until the thread on which it is called dies.
For example the statement,
t1. join () ;
cause the current thread to wait until the thread t1 dies. The join () method can throw an InterruptedException exception, if the current thread is interrupted by another thread, so you should put a call to join () in a try block and catch the exception. There also exists overloaded versions of join () method which takes a parameter of type long (i.e. void join (long nsec)). This parameter value specifies the number of milliseconds for which the current thread waits for the thread on which this method is called to die.
class MyThread extends Thread { double e ; public void run() { for(int i=0;i<15;i++) { e += 1.0/factorial(i); } } int factorial(int n) { if(n==0) return(1); else return(n * factorial(n-1)); } } public class JoinEx { public static void main(String[] args) { System.out.println("Main Thread Starts"); MyThread t1 = new MyThread(); t1.setName("Factorial Calulation Thread"); t1.start(); try { t1.join(); } catch(InterruptedException ex) { ex.printStackTrace(); } System.out.println("The value of e = " + t1.e); System.out.println("Main Thread Ends"); } }