The join Method: Basic Syntax and Purpose
What you'll learn: How to make one thread wait for another thread to finish using join().
The Problem join() Solves
When you start multiple threads, they run independently and concurrently. Often, however, you need one thread (typically the main thread) to wait until another thread completes its work before continuing. Without a mechanism to coordinate this, your program might try to use results before they're ready.
The join() method forces the calling thread to pause and wait until the target thread terminates. Think of it like waiting at a train junction: your train (the calling thread) must wait at the crossing until the other train (the target thread) passes completely through.
Basic Syntax
Thread worker = new Thread(() -> {
// Some long-running work
System.out.println("Worker thread executing...");
});
worker.start();
try {
worker.join(); // Main thread waits here until worker finishes
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
System.out.println("Worker has finished, continuing main thread");
How It Works
When you call worker.join(), the current thread (the one executing join()) transitions to the WAITING state until worker reaches the TERMINATED state. Once the worker thread completes its run() method, the waiting thread resumes execution.
Just like sleep(), join() throws InterruptedException, allowing other threads to interrupt the waiting if needed. You must handle this checked exception.
Key Takeaway: The join() method blocks the calling thread until the target thread completes, providing essential coordination between threads that depend on each other's completion.