久久精品人人爽,华人av在线,亚洲性视频网站,欧美专区一二三

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

136次閱讀
沒有評論

共計 1189 個字符,預計需要花費 3 分鐘才能閱讀完成。

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 來獲取任務的執行結果。可以使用 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 網 – 提供最優質的資源集合!

正文完
 
丸趣
版權聲明:本站原創文章,由 丸趣 2023-12-20發表,共計1189字。
轉載說明:除特殊說明外本站除技術相關以外文章皆由網絡搜集發布,轉載請注明出處。
評論(沒有評論)
主站蜘蛛池模板: 普安县| 平定县| 页游| 新蔡县| 雷山县| 莱州市| 建湖县| 清涧县| 桃园市| 沽源县| 泽库县| 肥乡县| 太保市| 合川市| 湘潭县| 任丘市| 隆昌县| 汶川县| 房产| 威信县| 江津市| 永泰县| 商城县| 衡南县| 丹阳市| 凌源市| 壤塘县| 忻城县| 景东| 田林县| 安国市| 永和县| 洪湖市| 遂溪县| 大名县| 共和县| 东台市| 广宗县| 福建省| 喀喇沁旗| 赤水市|