Joining a Thread in Java

The join() method in Java allows one thread to wait for the completion of another thread. When a thread calls the join() method on another thread, it pauses its execution until the thread it is joining has finished executing.

Key Points about Join Method:

Syntax of Join Method:

The basic syntax of the join() method is as follows:

public final void join() throws InterruptedException

Or to specify a timeout:

public final void join(long millis) throws InterruptedException

Example of Joining Threads in Java:

This example demonstrates how to use the join() method to wait for a thread to complete its execution.

Code Example

public class JoinExample extends Thread {
    public void run() {
        try {
            // Simulating some work with sleep
            Thread.sleep(2000);
            System.out.println(Thread.currentThread().getName() + " has completed.");
        } catch (InterruptedException e) {
            System.out.println("Thread was interrupted.");
        }
    }

    public static void main(String[] args) {
        JoinExample thread1 = new JoinExample();
        JoinExample thread2 = new JoinExample();

        thread1.start();
        thread2.start();

        try {
            // Wait for thread1 to finish
            thread1.join();
            // Wait for thread2 to finish
            thread2.join();
        } catch (InterruptedException e) {
            System.out.println("Main thread was interrupted.");
        }

        System.out.println("All threads have completed.");
    }
}

Output:

Thread-0 has completed.
Thread-1 has completed.
All threads have completed.

Conclusion:

The join() method is an essential tool for coordinating the execution of threads in Java. By using join(), you can ensure that certain tasks are completed before proceeding, which is crucial for maintaining the integrity of your program's logic and flow.

Best Practices: