Skip to main content

Java Concurrency - join()

Greeting!

Let's see the output of below program first.

public class ThreadJoin {

    public static void main(String[] args) {
        System.out.println("start");

        Thread t1 = new Thread(() -> System.out.println("in t1"));
        Thread t2 = new Thread(() -> System.out.println("in t2"));

        t1.start();
        t2.start();

        System.out.println("end");
    }

}


start
end
in t1
in t2


Notice that start and end print before it prints the messages from the threads. This is because thread are running separately hence main thread executes immediately.
What if we want to print end after executing t1 and t2? We can ask main thread to wait for finishing t1 and t2.
It is like a relay race. Second runner is waiting for the first runner to come and hand over the flag to him.
join - execution thread put on wait until this thread is finished.

public class ThreadJoin {

    public static void main(String[] args) {
        System.out.println("start");

        Thread t1 = new Thread(() -> System.out.println("in t1"));
        Thread t2 = new Thread(() -> System.out.println("in t2"));

        t1.start();
        t2.start();

        try {
            t1.join();
            t2.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("end");
    }

}


start
in t1
in t2
end


"main" thread waited for t1 and t2 to finish there tasks before printing "end".

In a case where the thread is dead locking or taking a long time to finish, join also accepts waiting time in milliseconds.



Comments