28 Apr 2015

Java Thread Join with Example

In java, join() methods allows one thread to wait for the complete execution of other thread.

Consider there are two threads T1 & T2, currently thread T1 is executing and we invoked join() method on T2 then execution of thread T1 is paused and waits for the completion of execution of Thread T2 and then it resumes.

Example:
class MyThread implements Runnable{

   @Override
   public void run(){
      System.out.println(i);
   }

}

public class JoinExample{

   public static void main(String args[]){
      Thread t = new Thread(new MyThread());
      t.start();

      try{
         t.join();
      }catch(InterruptedException e){
         e.printStackTrace();
      }

      System.out.println("Main Thread Ends"); 
   }

}
Thread Join Example


In the preceding example we created & started a thread 't' which prints 'i' value from 0 to 99 inside run() method. Then we are invoking join() method on this thread so that the current thread i.e., main thread waits for the complete execution of thread 't', and then only main thread prints 'End'.

Observations: 

Try to run the above program with and without invoking join() method on thread 't'.
  1. If you are invoking join() method then you will find sequence of numbers from 0 to 99 followed with End in the output

  2. If you are not invoking join() method then we can't expect specific output i.e., there's no guarantee of sequence of numbers from 0 to 99 in the output which you will find End at any place as main thread is not waiting for the execution of thread 't'





Popular Posts

Write to Us
Name
Email
Message