Java Thread Join Example

Introduction

The join method in Java is used to pause the execution of the current thread until the specified thread has finished executing. This is particularly useful when you need to ensure that a thread has completed its task before continuing with the rest of the program. The join method can be called on a thread instance, and there are three overloaded versions of it: join(), join(long millis), and join(long millis, int nanos).

Table of Contents

  1. join Method Variants
  2. Example: Using join Method
  3. Example: Using join(long millis) Method
  4. Example: Using join(long millis, int nanos) Method
  5. Conclusion

1. join Method Variants

join()

This method pauses the execution of the current thread until the specified thread completes.

Syntax:

public final void join() throws InterruptedException

join(long millis)

This method pauses the execution of the current thread for the specified number of milliseconds or until the specified thread completes, whichever comes first.

Syntax:

public final void join(long millis) throws InterruptedException

join(long millis, int nanos)

This method pauses the execution of the current thread for the specified number of milliseconds plus nanoseconds or until the specified thread completes, whichever comes first.

Syntax:

public final void join(long millis, int nanos) throws InterruptedException

2. Example: Using join Method

Let's create an example to demonstrate how to use the join method to wait for a thread to complete before continuing with the main thread.

Example:

class MyThread extends Thread {
    public MyThread(String name) {
        super(name); // Set the name of the thread
    }

    @Override
    public void run() {
        for (int i = 0; i < 3; i++) {
            System.out.println(Thread.currentThread().getName() + " is running.");
            try {
                Thread.sleep(500); // Sleep for 500 milliseconds
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        MyThread thread1 = new MyThread("Thread-1");
        MyThread thread2 = new MyThread("Thread-2");
        MyThread thread3 = new MyThread("Thread-3");

        thread1.start(); // Start thread1
        thread2.start(); // Start thread2
        thread3.start(); // Start thread3

        try {
            thread1.join(); // Wait for thread1 to finish
            thread2.join(); // Wait for thread2 to finish
            thread3.join(); // Wait for thread3 to finish
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

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

Output:

Thread-1 is running.
Thread-2 is running.
Thread-3 is running.
Thread-1 is running.
Thread-2 is running.
Thread-3 is running.
Thread-1 is running.
Thread-2 is running.
Thread-3 is running.
All threads have finished execution.

Explanation:

  • The MyThread class extends the Thread class and sets the name of the thread.
  • The run method prints the name of the current thread and then sleeps for 500 milliseconds.
  • In the main method, three MyThread objects are created and started.
  • The join method is called on each thread, ensuring that the main thread waits for all three threads to finish before printing "All threads have finished execution."

3. Example: Using join(long millis) Method

This example demonstrates using the join(long millis) method to wait for a specified amount of time or until the thread completes, whichever comes first.

Example:

class MyThread extends Thread {
    public MyThread(String name) {
        super(name); // Set the name of the thread
    }

    @Override
    public void run() {
        for (int i = 0; i < 5; i++) {
            System.out.println(Thread.currentThread().getName() + " is running.");
            try {
                Thread.sleep(1000); // Sleep for 1000 milliseconds
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        MyThread thread1 = new MyThread("Thread-1");

        thread1.start(); // Start thread1

        try {
            thread1.join(3000); // Wait for thread1 to finish or timeout after 3000 milliseconds
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("Main thread execution continues.");
    }
}

Output:

Thread-1 is running.
Thread-1 is running.
Thread-1 is running.
Main thread execution continues.
Thread-1 is running.
Thread-1 is running.

Explanation:

  • The join(long millis) method waits for thread1 to complete or 3000 milliseconds, whichever comes first.
  • After the timeout, the main thread resumes execution and prints "Main thread execution continues."

4. Example: Using join(long millis, int nanos) Method

This example demonstrates using the join(long millis, int nanos) method to wait for a specified amount of time, including nanoseconds, or until the thread completes, whichever comes first.

Example:

class MyThread extends Thread {
    public MyThread(String name) {
        super(name); // Set the name of the thread
    }

    @Override
    public void run() {
        for (int i = 0; i < 5; i++) {
            System.out.println(Thread.currentThread().getName() + " is running.");
            try {
                Thread.sleep(1000); // Sleep for 1000 milliseconds
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        MyThread thread1 = new MyThread("Thread-1");

        thread1.start(); // Start thread1

        try {
            thread1.join(2000, 500000); // Wait for thread1 to finish or timeout after 2000 milliseconds and 500,000 nanoseconds
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("Main thread execution continues.");
    }
}

Output:

Thread-1 is running.
Thread-1 is running.
Main thread execution continues.
Thread-1 is running.
Thread-1 is running.
Thread-1 is running.

Explanation:

  • The join(long millis, int nanos) method waits for thread1 to complete or 2000 milliseconds and 500,000 nanoseconds, whichever comes first.
  • After the timeout, the main thread resumes execution and prints "Main thread execution continues."

5. Conclusion

The join method in Java is used for controlling the execution flow of threads. By using the join, join(long millis), and join(long millis, int nanos) methods, you can ensure that a thread completes its execution before the main thread or other threads continue. This can help in coordinating tasks and ensuring that necessary conditions are met before proceeding.

Happy coding!

Comments