Java - Thread Thread Join

Introduction

You can use join method to wait for a thread to terminate.

The join() method of the Thread class throws a java.lang.InterruptedException, and your code should handle it.

Demo

public class Main {
  public static void main(String[] args) {
    Thread t1 = new Thread(Main::print);
    t1.start();/*from w  ww.jav  a 2s  . c o m*/

    try {
      t1.join(); // "main" thread waits until t1 is terminated
    } catch (InterruptedException e) {
      e.printStackTrace();
    }

    System.out.println("We are 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();
      }
    }
  }
}

Result

Note

The join() method of the Thread class is overloaded. It can accept a timeout argument.

If you 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.

A thread can join multiple threads like so:

t1.join(); // Join t1
t2.join(); // Join t2
t3.join(); // Join t3

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