Thread Join Example in Java

Thread Class provides join() method Basically It will wait for Thread to die.Consider following scenario where we haven't used join and observe the output.

In Scenarion1, Output is not sequential and one Thread goes to sleep and Thread scheduler picks up another thread and start executing.

Scenario1 : Situation where there is no Join :

package com.anuj.threading;

/**
 * Thread Join Example
 * @author Anuj
 *
 */
class ThreadJoinExample extends Thread{

 @Override
 public void run() {
  for(int i=1;i<=5;i++){
   System.out.println(Thread.currentThread().getName() + " - "+i);
   
   try {
    Thread.sleep(500);
   } catch (InterruptedException e) {
    e.printStackTrace();
   }
  }
 }
 
 /**
  * @param args
  */
 public static void main(String[] args) {
  ThreadJoinExample t1 = new ThreadJoinExample();
  ThreadJoinExample t2 = new ThreadJoinExample();
  t1.setName("Thread1");
  t2.setName("Thread2");
  
  t1.start();
  System.out.println(t1.getName() + " : " + t1.isAlive());
  
  /*try{
   t1.join();
   System.out.println(t1.getName() + " : " + t1.isAlive());
  }
  catch(Exception e){
   e.printStackTrace();
  }*/
    
  System.out.println(t2.getName() + " : " + t2.isAlive());
  t2.start();
 }
}
Output :Thread1 : true
Thread1 - 1
Thread1 - 2
Thread1 - 3
Thread1 - 4
Thread1 - 5
Thread1 : false
Thread2 : false
Thread2 - 1
Thread2 - 2
Thread2 - 3
Thread2 - 4
Thread2 - 5

No comments:

Post a Comment