Java Thread Tutorial - Java Thread Join








A thread can wait for another thread to die or terminate.

Example

Suppose there are two threads, t1 and t2. If the thread t1 calls t2.join(), thread t1 starts waiting until thread t2 is terminated.

The call t2.join() blocks until t2 terminates.

Using the join() method in a program is useful if one of the threads cannot proceed until another thread has finished executing.

The following code has an example, it prints a message on the standard output when the program has finished executing.

public class Main {
  public static void main(String[] args) {
    Thread t1 = new Thread(Main::print);
    t1.start();//from  ww  w .j  ava  2  s. c o  m
    System.out.println("Done.");
  }

  public static void print() {
    for (int i = 1; i <= 5; i++) {
      try {
        System.out.println("Counter: " + i);
        Thread.sleep(1000);
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
    }
  }
}

The code above generates the following result.

From the result we can see that the "Done." is printed before the message from the real thread. t1.start(); just starts the thread, it will block the execution and wait for the thread to finish.

The following code uses join() to wait for the thread to finish then print "Done."

public class Main {
  public static void main(String[] args) {
    Thread t1 = new Thread(Main::print);
    t1.start();
    try {
      t1.join();
      // "main" thread waits until t1 is terminated
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
    System.out.println("Done.");
  }

  public static void print() {
    for (int i = 1; i <= 5; i++) {
      try {
        System.out.println("Counter: " + i);
        Thread.sleep(1000);
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
    }
  }
}

The code above generates the following result.





Note

The join() method of the Thread class is overloaded.

Its other two versions accept a timeout argument.

If we use the join() method with a timeout, the caller thread will wait until the thread on which it is called is terminated or the timeout has elapsed.

We should call the join() method of a thread after it has been started.

If we call the join() method on a not-started thread, it returns immediately.

If we call the join() method on a terminated thread, it returns immediately.