In Java, the join() method is used to wait for a thread to finish its execution before continuing with the rest of the program. The join() method causes the current thread to pause its execution and wait for the specified thread to terminate.
The join() method has several overloaded versions with different parameters:
public final void join() throws InterruptedException:This version of the join() method waits for the specified thread to complete its execution before continuing with the rest of the program.
public final synchronized void join(long millis) throws InterruptedException:This version of the join() method waits for the specified thread to complete its execution or until the specified number of milliseconds have passed, whichever comes first.
public final synchronized void join(long millis, int nanos) throws InterruptedExceptionThis version of the join() method waits for the specified thread to complete its execution or until the specified number of milliseconds and nanoseconds have passed, whichever comes first.
Here's an example of how to use the join() method to wait for a thread to complete its execution:
public class JoinExample {
public static void main(String[] args) throws InterruptedException {
Thread thread = new Thread(() -> {
try {
Thread.sleep(2000);
System.out.println("Thread completed.");
} catch (InterruptedException e) {
e.printStackTrace();
}
});
System.out.println("Starting thread...");
thread.start();
System.out.println("Waiting for thread to complete...");
thread.join();
System.out.println("Thread has completed. Continuing with the rest of the program.");
}
}
In this example, the main() method of the JoinExample class creates a new thread and starts it. It then calls the join() method on the thread, which causes the main thread to wait for the new thread to complete its execution. Once the new thread has completed, the main thread prints "Thread has completed. Continuing with the rest of the program." to the console and continues with the rest of the program.
Overall, the join() method is a useful tool for coordinating the execution of multiple threads in a program. It allows threads to be synchronized and ensures that the correct order of operations is maintained.