Java.Multithreading.How does Thread.join() work?

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

  1. Suppose you have a main thread and another thread t1.
  2. 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 the join() call.

🔧 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() uses wait() and notifyAll():
    • When join() is called, the current thread waits on the Thread object’s monitor.
    • When the thread finishes (run() method exits), it calls notifyAll() to wake up any threads waiting on it.

🕒 Overloaded Versions

  • join() — waits indefinitely.
  • join(long millis) — waits at most millis 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 with sleep()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.
This entry was posted in Без рубрики. Bookmark the permalink.