Sobes.tech
Middle

How does the Thread.join() method work?

sobes.tech AI

Answer from AI

The Thread.join() method causes the current executing thread to wait for the thread on which join is called to finish.

When calling otherThread.join(), the current thread (for example, the main thread) is blocked until otherThread completes its execution (its run() method returns control).

You can specify a timeout in milliseconds or in milliseconds and nanoseconds:

  • otherThread.join(long millis): waits for a maximum of millis milliseconds.
  • otherThread.join(long millis, int nanos): waits for a maximum of millis milliseconds and nanos nanoseconds.

If the specified timeout expires and the thread has not finished, the current thread is unblocked and continues execution.

Thread.join() can throw an InterruptedException if the current thread is interrupted while waiting. In this case, the wait is terminated.

Example:

// Create and start a new thread
Thread worker = new Thread(() -> {
    try {
        // Simulate work
        Thread.sleep(2000);
        System.out.println("Worker thread finished.");
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
});

worker.start();

try {
    // Main thread waits for the worker thread to finish
    worker.join();
    System.out.println("Main thread continues after worker finished.");
} catch (InterruptedException e) {
    e.printStackTrace();
}

Important: join() synchronizes the execution of one thread with the completion of another. This is useful when you need to ensure that a certain task is completed before continuing execution in another thread.