溫馨提示×

java等待多線程執行完成的方法是什么

小億
217
2023-09-15 13:06:28
欄目: 編程語言

Java中等待多線程執行完成的方法有以下幾種:

  1. 使用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();
}
// 所有線程執行完成后繼續執行的代碼
  1. 使用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();
}
// 所有線程執行完成后繼續執行的代碼
  1. 使用ExecutorService和Future:ExecutorService是一個線程池,可以提交多個任務執行,并通過Future來獲取任務的執行結果??梢允褂肍uture的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();
// 所有線程執行完成后繼續執行的代碼

這些方法可以根據具體的場景選擇使用。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女