Thread Join In Java with example - Java @ Desk

Saturday, March 29, 2014

Thread Join In Java with example

Thread Join In Java with example

Join in threads as the name suggest is to join the thread with another thread i.e. if two threads are running Thread A and Thread B such that

Thread B joins Thread A then, Thread A will wait for the Thread B to finish its execution.

join() method in Thread class is a final method and it has its overloaded versions too. The overloaded version takes the timeout parameter i.e. if the join thread does not finishes within the timeout the other thread will resume its execution.

join() method does not takes any timeout parameter, so it waits indefinetly for the thread to finish its execution

join(long milliseconds) - the joining thread will wait for milliseconds passed and resume execution.

The main advantage of join is to run the thread in series or in particular order.

Client file for join example for infinite wait - In the below file if while(true) method is uncommented, then the main thread will wait indefinetly for the thread to gets over.

Execution Order
1) Main Started
2) Runnable Thread Started - Thread-0
3) Wait for the Thread-0 to get over
4) Runnable Over - Thread-0
5) Main Thread Over

package test;

public class ThreadJoin implements Runnable {

 @Override
 public void run() {
  try {
   System.out.println("Runnable Thread Started - "
     + Thread.currentThread().getName());
   //while (true)
    Thread.sleep(10000);

  } catch (InterruptedException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  System.out.println("Runnable Over - "
    + Thread.currentThread().getName());
 }

 public static void main(String args[]) throws Exception {
  System.out.println("Main Started");
  Thread thread = new Thread(new ThreadJoin());

  thread.start();
  thread.join();

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

}






No comments:

Post a Comment