To wait until all threads finish their work in Java, you can use the Thread.join()
method or higher-level constructs like ExecutorService
with shutdown
and awaitTermination
. Here's how you can achieve this using both approaches:
Thread.join()
:The join()
method is called on a thread, and it waits for that thread to finish before proceeding. You can use this method for each thread you want to wait for.
public class WaitUntilThreadsFinish { public static void main(String[] args) throws InterruptedException { Thread thread1 = new Thread(() -> { // Thread 1's work here }); Thread thread2 = new Thread(() -> { // Thread 2's work here }); // Start the threads thread1.start(); thread2.start(); // Wait for both threads to finish thread1.join(); thread2.join(); // All threads have finished their work System.out.println("All threads have finished."); } }
In this example, thread1.join()
and thread2.join()
block until thread1
and thread2
have completed their work.
ExecutorService
:ExecutorService
provides a higher-level and more flexible way to manage threads. You can use it to submit tasks and wait for their completion using awaitTermination()
.
import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; public class WaitUntilThreadsFinishWithExecutor { public static void main(String[] args) throws InterruptedException { ExecutorService executor = Executors.newFixedThreadPool(2); executor.submit(() -> { // Task 1's work here }); executor.submit(() -> { // Task 2's work here }); // Shutdown the executor, preventing it from accepting new tasks executor.shutdown(); // Wait for all tasks to finish (or timeout after a specified time) if (executor.awaitTermination(5, TimeUnit.SECONDS)) { // All tasks have finished System.out.println("All tasks have finished."); } else { // Timeout occurred (tasks are still running) System.out.println("Timeout: Some tasks are still running."); } } }
In this example, we create an ExecutorService
with two threads and submit tasks to it. After submitting tasks, we shut down the executor and use awaitTermination()
to wait for all tasks to finish or timeout after a specified duration (5 seconds in this case).
Using ExecutorService
is a more scalable and robust way to manage threads, especially when dealing with a larger number of tasks.
android-popupwindow onmousedown pivot ng-packagr words debian-based apollo mediarecorder mean-stack hp-uft