Sunday 2 March 2014

Thread join

Suppose you divided a big problem into small tasks, lets say one big problem is divided into 5 small tasks. So to solve the whole problem. All the 5 tasks must be completed, one task may finishes immediately, other takes 5 minutes, and other may take 1 hour etc., Your program must wait until all the tasks finishes its execution. Here the join method comes into picture.

The join() method of Thread can be used to cause the current thread to block waiting for the specified thread to die.

Example
class JoinEx implements Runnable{
 public void run(){
  try{
   Thread.currentThread().sleep(1000);
   System.out.println(Thread.currentThread().getName() + " Finishes execution");
  }
  catch(Exception e){
   System.out.println(e);
  }
 }

 public static void main(String args[])throws Exception{
  JoinEx obj1 = new JoinEx();
  JoinEx obj2 = new JoinEx();
  JoinEx obj3 = new JoinEx();
  JoinEx obj4 = new JoinEx();
  JoinEx obj5 = new JoinEx();

  Thread task1 = new Thread(obj1);
  Thread task2 = new Thread(obj1);
  Thread task3 = new Thread(obj1);
  Thread task4 = new Thread(obj1);
  Thread task5 = new Thread(obj1);

  task1.start();
  task2.start();
  task3.start();
  task4.start();
  task5.start();

  task1.join();
  task2.join();
  task3.join();
  task4.join();
  task5.join();

  System.out.println("All tasks completed successfully");
 }
}
  
Sample Output
Thread-2 Finishes execution
Thread-1 Finishes execution
Thread-3 Finishes execution
Thread-4 Finishes execution
Thread-0 Finishes execution
All tasks completed successfully

Overloaded methods of join
public final void join(long millis) :Waits at most millis milliseconds for this thread to die. A timeout of 0 means to wait forever.

public final void join(long millis, int nanos) : Waits at most millis milliseconds plus nanos nanoseconds for this thread to die.

Join method throws InterruptedException, when the thread interrupted.


Inter Thread Communication                                                 producer Consumer problem                                                 Home

No comments:

Post a Comment