Thread.join()
in Java is a method that allows one thread to wait for the completion of another thread before continuing its execution. It’s a synchronization mechanism that ensures a thread finishes before the calling thread proceeds.
✅ How Thread.join()
Works – Step by Step
- Suppose you have a main thread and another thread
t1
. - When you call
t1.join()
from the main thread:- The main thread pauses execution and waits until
t1
completes. - Once
t1
finishes, the main thread resumes execution from the line after thejoin()
call.
- The main thread pauses execution and waits until
🔧 Basic Example
public class JoinExample {
public static void main(String[] args) throws InterruptedException {
Thread t1 = new Thread(() -> {
System.out.println("Thread t1 is running...");
try {
Thread.sleep(2000); // Simulate work
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Thread t1 finished.");
});
t1.start();
t1.join(); // Main thread waits here until t1 completes
System.out.println("Main thread resumes after t1 is done.");
}
}
🧠 Output (with a 2-second pause in between):
Thread t1 is running...
Thread t1 finished.
Main thread resumes after t1 is done.
🧩 Under the Hood
- Internally,
join()
useswait()
andnotifyAll()
:- When
join()
is called, the current thread waits on theThread
object’s monitor. - When the thread finishes (
run()
method exits), it callsnotifyAll()
to wake up any threads waiting on it.
- When
🕒 Overloaded Versions
join()
— waits indefinitely.join(long millis)
— waits at mostmillis
milliseconds.join(long millis, int nanos)
— more precise control with nanosecond precision.
❗ Important Notes
- Always handle
InterruptedException
, which may occur if the waiting thread is interrupted. join()
should not be confused withsleep()
—sleep()
just pauses the current thread,join()
waits for another thread to finish.join()
should be used cautiously in multi-threaded environments to avoid deadlocks.