Java Thread join() Method

The Thread.join() method in Java is used to wait for a thread to terminate.

Table of Contents

  1. Introduction
  2. join() Method Syntax
  3. Overloaded join() Methods
  4. Examples
    • Basic Usage
    • Using join(long millis)
    • Using join(long millis, int nanos)
    • Using join(Duration duration)
  5. Real-World Use Case
  6. Conclusion

Introduction

The Thread.join() method allows one thread to wait for the completion of another thread. This is useful when you want to ensure that a thread has finished executing before the main program or another thread continues its execution.

join() Method Syntax

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

public final void join() throws InterruptedException

Throws:

  • InterruptedException if any thread has interrupted the current thread.

Overloaded join() Methods

In addition to the basic join() method, there are several overloaded versions of the method that allow you to specify a maximum wait time.

join(long millis)

public final void join(long millis) throws InterruptedException

Waits at most millis milliseconds for this thread to terminate.

join(long millis, int nanos)

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

Waits at most millis milliseconds plus nanos nanoseconds for this thread to terminate.

join(Duration duration)

public final boolean join(Duration duration) throws InterruptedException

Waits for this thread to terminate for up to the given waiting duration.

Examples

Basic Usage

To demonstrate the basic usage of join(), we will create a thread and wait for it to finish before continuing the main thread's execution.

Example

public class JoinExample {
    public static void main(String[] args) {
        Thread thread = new Thread(() -> {
            try {
                Thread.sleep(2000); // Simulate work
                System.out.println("Thread has finished.");
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        });

        thread.start();

        try {
            thread.join(); // Wait for the thread to finish
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }

        System.out.println("Main thread resumes after thread completion.");
    }
}

Output:

Thread has finished.
Main thread resumes after thread completion.

Using join(long millis)

You can use the join(long millis) method to wait for a thread to finish for a specified time.

Example

public class JoinMillisExample {
    public static void main(String[] args) {
        Thread thread = new Thread(() -> {
            try {
                Thread.sleep(5000); // Simulate work
                System.out.println("Thread has finished.");
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        });

        thread.start();

        try {
            thread.join(2000); // Wait for up to 2000 milliseconds
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }

        System.out.println("Main thread resumes after waiting for 2000 milliseconds.");
    }
}

Output:

Main thread resumes after waiting for 2000 milliseconds.
Thread has finished.

Using join(long millis, int nanos)

You can use the join(long millis, int nanos) method to wait for a thread to finish for a specified time in milliseconds and nanoseconds.

Example

public class JoinMillisNanosExample {
    public static void main(String[] args) {
        Thread thread = new Thread(() -> {
            try {
                Thread.sleep(3000); // Simulate work
                System.out.println("Thread has finished.");
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        });

        thread.start();

        try {
            thread.join(2000, 500000); // Wait for up to 2000 milliseconds and 500000 nanoseconds
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }

        System.out.println("Main thread resumes after waiting for the specified duration.");
    }
}

Output:

Main thread resumes after waiting for the specified duration.
Thread has finished.

Using join(Duration duration)

You can use the join(Duration duration) method to wait for a thread to finish for a specified Duration.

Example

import java.time.Duration;

public class JoinDurationExample {
    public static void main(String[] args) {
        Thread thread = new Thread(() -> {
            try {
                Thread.sleep(4000); // Simulate work
                System.out.println("Thread has finished.");
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        });

        thread.start();

        try {
            thread.join(Duration.ofMillis(2000)); // Wait for up to 2000 milliseconds
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }

        System.out.println("Main thread resumes after waiting for the specified duration.");
    }
}

Output:

Main thread resumes after waiting for the specified duration.
Thread has finished.

Real-World Use Case

Ensuring Task Completion

In real-world scenarios, you might want to ensure that certain tasks are completed before proceeding with further operations. The join() method can be used to synchronize threads and ensure that dependent tasks are completed before moving on.

Example

public class TaskCompletionExample {
    public static void main(String[] args) {
        Thread taskThread = new Thread(() -> {
            try {
                Thread.sleep(3000); // Simulate task
                System.out.println("Task has been completed.");
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        });

        taskThread.start();

        try {
            taskThread.join(); // Wait for the task to complete
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }

        System.out.println("Proceeding with the next step after task completion.");
    }
}

Output:

Task has been completed.
Proceeding with the next step after task completion.

Conclusion

The Thread.join() method in Java provides a way to wait for a thread to terminate. By understanding how to use this method and its overloaded versions, you can manage thread synchronization and ensure that dependent tasks are completed before proceeding. Whether you are working with single-threaded or multi-threaded environments, the join() method offers used for controlling thread execution flow in Java.

Comments