Course contentsShow
← Java
Lesson 2615 of 2,87048. Concurrency FundamentalsFree lesson

Joining Multiple Threads in Sequence

Coordinate multiple worker threads by calling join on each in turn to ensure ordered completion.

Joining Multiple Threads in Sequence

You'll learn how to coordinate multiple worker threads by calling join() on each in turn to ensure they complete in a specific order.

The Core Idea

When you have multiple threads doing independent work, you might need the main thread to wait for them all to finish before proceeding—and sometimes you care about the order in which you wait. By calling join() on each thread sequentially, you create a synchronization point where the calling thread blocks until each worker completes, one after another.

Think of it like a project manager waiting for reports from three teams. You might say, "I'll wait for Team A's report, then Team B's, then Team C's." Even if Team C finishes first, you don't check their report until you've received A's and B's.

How It Works

Thread t1 = new Thread(() -> {
    // Task 1
    System.out.println("Task 1 running");
});

Thread t2 = new Thread(() -> {
    // Task 2
    System.out.println("Task 2 running");
});

Thread t3 = new Thread(() -> {
    // Task 3
    System.out.println("Task 3 running");
});

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

// Join in sequence
t1.join();  // Block until t1 finishes
t2.join();  // Then block until t2 finishes
t3.join();  // Then block until t3 finishes

System.out.println("All tasks complete");

The main thread waits at each join() call. Even if t3 finishes before t1, the main thread won't proceed past t1.join() until t1 terminates.

Key Takeaway: Calling join() sequentially on multiple threads ensures the calling thread waits for each worker to complete in the specified order, creating predictable synchronization points in your concurrent code.