April 1, 2011

Thread Join - joining at the end of a thread

The join() method on a Thread instance is used to join the current thread at the end of the thread on which the  join is invoked. That is, the current thread will suspend its execution (and will not resume execution) until the thread instance on which the join is invoked completes its execution.

In the example code below, the 2 thread instances t1 and t2 are names run-1 and run-2 respectively and invoked. In the run, the join() method is invoked on the thread instance t2 if the currently executing thread is t1, that is, thread t1 joins on thread t2. Therefore, execution of thread t1 is suspended and does not resume until thread t2 completes execution. After t2 completes its execution, thread t1 can then resume its execution.


package info.icontraining.threads;

public class Test implements Runnable {

   private static Thread t1, t2;
 
   public void run() {
      try {
         if (Thread.currentThread().getName().equals("run-1") {
            t2.join();
         }
   
         for (int i=0;i<50;i++) {
            System.out.println(i + ": In " + 
               Thread.currentThread().getName() + " thread");
         }
   
      } catch (InterruptedException e) {
         e.printStackTrace();
      }    
   }
     
   public static void main(String[] args)
             throws InterruptedException {
  
      t1 = new Thread(new Test());
      t1.setName("run-1");
      t1.start();
  
      t2 = new Thread(new Test());
      t2.setName("run-2");
      t2.start();
   }
}

No comments:

Post a Comment