Joining Threads in Java



java.lang.Thread class provides a method join() which serves the following purposes usign its overloaded version.


  • join() − The current thread invokes this method on a second thread, causing the current thread to block until the second thread terminates.

  • join(long millisec) − The current thread invokes this method on a second thread, causing the current thread to block until the second thread terminates or the specified number of milliseconds passes.

  • join(long millisec, int nanos) − The current thread invokes this method on a second thread, causing the current thread to block until the second thread terminates or the specified number of milliseconds + nanoseconds passes.

See the below example demonstrating the concept.

Example

 Live Demo

class CustomThread implements Runnable {
   public void run() {
      System.out.println(Thread.currentThread().getName() + " started.");
      try {
         Thread.sleep(500);
      } catch (InterruptedException e) {
         System.out.println(Thread.currentThread().getName() + " interrupted.");
      }
      System.out.println(Thread.currentThread().getName() + " exited.");
   }
}
public class Tester {
   public static void main(String args[]) throws InterruptedException {
      Thread t1 = new Thread( new CustomThread(), "Thread-1");
      t1.start();
      //main thread class the join on t1
      //and once t1 is finish then only t2 can start
      t1.join();
      Thread t2 = new Thread( new CustomThread(), "Thread-2");
      t2.start();
      //main thread class the join on t2
      //and once t2 is finish then only t3 can start
      t2.join();
      Thread t3 = new Thread( new CustomThread(), "Thread-3");
      t3.start();
   }
}

Output

Thread-1 started.
Thread-1 exited.
Thread-2 started.
Thread-2 exited.
Thread-3 started.
Thread-3 exited.

Advertisements