Java programming language logo

Thread Join

When a thread has to wait to another thread to finish, the join method can be used. The join method pauses the current thread until the other thread is alive or for a specified duration.

The join method throws InterruptedException. This is important when a thread should be interrupted. To learn more about thread interruption, see the Thread Interruption page. In the below examples, the throws clause is just added to the main methods.

Thread Join without Duration

In the next example, the thread calculates the sum of 1+2+3+4 and stores the result of it in the result field. The main thread starts the addition thread and prints out the value of result field. Starting a new thread takes some time and the operation also, so the main thread has to wait for the started thread to finish; otherwise, the main method prints out the result before it gets calculated.

The t.join() pauses the main thread until the t thread finishes the addition.


package com.programcodex.concurrency.thread;

import java.util.stream.IntStream;

public class ThreadJoin implements Runnable {

    private int result;

    @Override
    public void run() {
        print("Starting the addition...");
        result = IntStream.range(1, 5).sum();
        print("Addition is done.");
    }

    public int getResult() {
        return result;
    }

    private static void print(String msg) {
        String threadName = Thread.currentThread().getName();
        System.out.format("%s: %s%n", threadName, msg);
    }

    public static void main(String[] args) throws InterruptedException {
        ThreadJoin threadJoin = new ThreadJoin();
        Thread t = new Thread(threadJoin);
        t.start();

        t.join(); // What if we comment this out?

        print("The result is " + threadJoin.getResult());
    }
}

The output of the above class:

Thread Join

The output of the above class, if we leave out the join and remove the t.join() line.

Thread Join

Thread Join with Duration

The join() method makes the thread waiting until the other thread is alive. If the other thread never finishes, the thread will wait forever. To solve this problem, the join method has an overloaded version that takes a maximum duration time in milliseconds. When the time expires, and the other thread is still alive, the waiting thread continues its execution.

Important to mention, this time period cannot be considered to be exact. It depends on the OS how precisely can handle it.

In the next example, the main thread starts a long running thread, that runs for 4 seconds. The main thread waits for it 1 second, and if it is still alive, waits another seconds, and so on.

Now the main thread actually waits for the other thread until that dies because the join is called in a while loop, but without that, the main thread would continue the execution after 1 second.

The isAlive returns with true if the thread still running.


package com.programcodex.concurrency.thread;

import java.time.LocalTime;
import java.time.format.DateTimeFormatter;

public class ThreadJoinWithDuration implements Runnable {

    private static DateTimeFormatter dtf = 
            DateTimeFormatter.ofPattern("HH:mm:ss");

    @Override
    public void run() {
        print("Starting a long running operation.");

        try {
            Thread.sleep(4_000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        print("I'm done.");
    }

    private static void print(String msg) {
        String time = dtf.format(LocalTime.now());
        String threadName = Thread.currentThread().getName();
        System.out.format("%s %s: %s%n", time, threadName, msg);
    }

    public static void main(String[] args) throws InterruptedException {
        Thread thread = new Thread(new ThreadJoinWithDuration());
        thread.start();

        while (thread.isAlive()) {
            print("Waiting for the thread...");
            thread.join(1000);
        }

        print("Finally it's done.");
    }
}

The output of the above class:

Thread Join with Duration