Thread Java 30 days- day 10(Join)
In the earlier sections, you’ve encountered the method “join.” So, let me explain what join is. Join is a method in Java’s multithreading mechanism used to wait for a thread to complete its execution. Let me provide an explanation of how to use the `join()` method.
In Java, when you create and start a thread, the main thread and that thread will run concurrently. Sometimes, you might want to wait for a specific thread to finish its execution before continuing with the main thread’s execution. This is where the `join()` method comes into play. Here’s a basic usage example of the `join()` method:
public class ComplexJoinExample {
public static void main(String[] args) throws InterruptedException {
Thread task1 = new Thread(() -> {
System.out.println("Task 1 started");
try {
Thread.sleep(3000); // Simulating task 1 execution time
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Task 1 completed");
});
Thread task2 = new Thread(() -> {
try {
task1.join(); // Wait for task 1 to complete
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Task 2 started");
try {
Thread.sleep(2000); // Simulating task 2 execution time
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Task 2 completed");
});
task1.start();
task2.start();
task2.join(); // Wait for task 2 to complete
System.out.println("Main thread continues execution");
}
}
Jumping back to the previous discussion about ExecutorService, it’s important to note that using ExecutorService does not require manual invocation of the `join()` method. This is because ExecutorService itself manages thread execution and waiting.
When you submit tasks to an ExecutorService for execution, it automatically creates and manages threads to execute those tasks. Then, once all tasks are completed, `executorService.awaitTermination()` will wait for all tasks in the thread pool to complete, without the need to manually use `join()`.