共計 1189 個字符,預計需要花費 3 分鐘才能閱讀完成。
Java 中等待多線程執行完成的方法有以下幾種:
- 使用 Thread 的 join 方法:調用線程的 join 方法可以等待該線程執行完成。例如,如果線程 A 執行了線程 B 的 join 方法,那么線程 A 會阻塞,直到線程 B 執行完成。
Thread thread1 = new Thread(() -> {// 線程 1 的任務});
Thread thread2 = new Thread(() -> {// 線程 2 的任務});
thread1.start();
thread2.start();
try {thread1.join();
thread2.join();} catch (InterruptedException e) {e.printStackTrace();
}
// 所有線程執行完成后繼續執行的代碼
- 使用 CountDownLatch 類:CountDownLatch 是一個線程同步的工具類,可以用來等待一組線程執行完成。通過 CountDownLatch 的 await 方法可以等待線程執行完成。
CountDownLatch latch = new CountDownLatch(2);
Thread thread1 = new Thread(() -> {
// 線程 1 的任務
latch.countDown();});
Thread thread2 = new Thread(() -> {
// 線程 2 的任務
latch.countDown();});
thread1.start();
thread2.start();
try {latch.await();
} catch (InterruptedException e) {e.printStackTrace();
}
// 所有線程執行完成后繼續執行的代碼
- 使用 ExecutorService 和 Future:ExecutorService 是一個線程池,可以提交多個任務執行,并通過 Future 來獲取任務的執行結果。可以使用 Future 的 get 方法等待所有任務執行完成。
ExecutorService executorService = Executors.newFixedThreadPool(2);
List<Future> futures = new ArrayList();
futures.add(executorService.submit(() -> {// 線程 1 的任務}));
futures.add(executorService.submit(() -> {// 線程 2 的任務}));
for (Future future : futures) {
try {future.get();
} catch (InterruptedException | ExecutionException e) {e.printStackTrace();
}
}
executorService.shutdown();
// 所有線程執行完成后繼續執行的代碼
這些方法可以根據具體的場景選擇使用。
丸趣 TV 網 – 提供最優質的資源集合!
正文完