Java多種方法實現等待所有子線程完成再繼續執行

来源:https://www.cnblogs.com/larrydpk/archive/2023/03/08/17195498.html
-Advertisement-
Play Games

簡介 在現實世界中,我們常常需要等待其它任務完成,才能繼續執行下一步。Java實現等待子線程完成再繼續執行的方式很多。我們來一一查看一下。 Thread的join方法 該方法是Thread提供的方法,調用join()時,會阻塞主線程,等該Thread完成才會繼續執行,代碼如下: private st ...


簡介

在現實世界中,我們常常需要等待其它任務完成,才能繼續執行下一步。Java實現等待子線程完成再繼續執行的方式很多。我們來一一查看一下。

Thread的join方法

該方法是Thread提供的方法,調用join()時,會阻塞主線程,等該Thread完成才會繼續執行,代碼如下:

private static void threadJoin() {
  List<Thread> threads = new ArrayList<>();

  for (int i = 0; i < NUM; i++) {
    Thread t = new Thread(new PkslowTask("Task " + i));
    t.start();
    threads.add(t);
  }
  threads.forEach(t -> {
    try {
      t.join();
    } catch (InterruptedException e) {
      throw new RuntimeException(e);
    }
  });

  System.out.println("threadJoin Finished All Tasks...");

}

結果:

Task 6 is running
Task 9 is running
Task 3 is running
Task 4 is running
Task 7 is running
Task 0 is running
Task 2 is running
Task 1 is running
Task 5 is running
Task 8 is running
Task 1 is completed
Task 8 is completed
Task 6 is completed
Task 4 is completed
Task 3 is completed
Task 0 is completed
Task 7 is completed
Task 9 is completed
Task 2 is completed
Task 5 is completed
threadJoin Finished All Tasks...

CountDownLatch

CountDownLatch是一個很好用的併發工具,初始化時要指定線程數,如10。在子線程調用countDown()時計數減1。直到為0時,await()方法才不會阻塞。代碼如下:

private static void countDownLatch() {
  CountDownLatch latch = new CountDownLatch(NUM);
  for (int i = 0; i < NUM; i++) {
    Thread t = new Thread(() -> {
      System.out.println("countDownLatch running...");
      try {
        Thread.sleep(1000);
        System.out.println("countDownLatch Finished...");
        latch.countDown();
      } catch (InterruptedException e) {
        throw new RuntimeException(e);
      }
    });
    t.start();
  }

  try {
    latch.await();
  } catch (InterruptedException e) {
    throw new RuntimeException(e);
  }
  System.out.println("countDownLatch Finished All Tasks...");
}

結果:

countDownLatch running...
countDownLatch running...
countDownLatch running...
countDownLatch running...
countDownLatch running...
countDownLatch running...
countDownLatch running...
countDownLatch running...
countDownLatch running...
countDownLatch running...
countDownLatch Finished...
countDownLatch Finished...
countDownLatch Finished...
countDownLatch Finished...
countDownLatch Finished...
countDownLatch Finished...
countDownLatch Finished...
countDownLatch Finished...
countDownLatch Finished...
countDownLatch Finished...
countDownLatch Finished All Tasks...

CyclicBarrier

CyclicBarrier與CountDownLatch類似,但CyclicBarrier可重置,可重用。代碼如下:

private static void cyclicBarrier() {
  CyclicBarrier barrier = new CyclicBarrier(NUM + 1);

  for (int i = 0; i < NUM; i++) {
    Thread t = new Thread(() -> {
      System.out.println("cyclicBarrier running...");
      try {
        Thread.sleep(1000);
        System.out.println("cyclicBarrier Finished...");
        barrier.await();
      } catch (InterruptedException | BrokenBarrierException e) {
        throw new RuntimeException(e);
      }
    });
    t.start();
  }

  try {
    barrier.await();
  } catch (InterruptedException | BrokenBarrierException e) {
    throw new RuntimeException(e);
  }
  System.out.println("cyclicBarrier Finished All Tasks...");
}

結果:

cyclicBarrier running...
cyclicBarrier running...
cyclicBarrier running...
cyclicBarrier running...
cyclicBarrier running...
cyclicBarrier running...
cyclicBarrier running...
cyclicBarrier running...
cyclicBarrier running...
cyclicBarrier running...
cyclicBarrier Finished...
cyclicBarrier Finished...
cyclicBarrier Finished...
cyclicBarrier Finished...
cyclicBarrier Finished...
cyclicBarrier Finished...
cyclicBarrier Finished...
cyclicBarrier Finished...
cyclicBarrier Finished...
cyclicBarrier Finished...
cyclicBarrier Finished All Tasks...

executorService.isTerminated()

ExecutorService調用shutdown()方法後,可以通過方法isTerminated()來判斷任務是否完成。代碼如下:

private static void executeServiceIsTerminated() {
  ExecutorService executorService = Executors.newFixedThreadPool(THREADS);
  IntStream.range(0, NUM)
    .forEach(i -> executorService.execute(new PkslowTask("Task " + i)));
  executorService.shutdown();
  while (!executorService.isTerminated()) {
    //waiting...
  }
  System.out.println("executeServiceIsTerminated Finished All Tasks...");

}

結果:

Task 0 is running
Task 2 is running
Task 1 is running
Task 3 is running
Task 4 is running
Task 0 is completed
Task 2 is completed
Task 5 is running
Task 4 is completed
Task 7 is running
Task 3 is completed
Task 1 is completed
Task 8 is running
Task 6 is running
Task 9 is running
Task 5 is completed
Task 9 is completed
Task 7 is completed
Task 6 is completed
Task 8 is completed
executeServiceIsTerminated Finished All Tasks...

executorService.awaitTermination

executorService.awaitTermination方法會等待任務完成,並給一個超時時間,代碼如下:

private static void executeServiceAwaitTermination() {
  ExecutorService executorService = Executors.newFixedThreadPool(THREADS);
  IntStream.range(0, NUM)
    .forEach(i -> executorService.execute(new PkslowTask("Task " + i)));
  executorService.shutdown();

  try {
    if (!executorService.awaitTermination(1, TimeUnit.MINUTES)) {
      executorService.shutdownNow();
    }
  } catch (InterruptedException e) {
    throw new RuntimeException(e);
  }
  System.out.println("executeServiceAwaitTermination Finished All Tasks...");
}

結果:

Task 0 is running
Task 1 is running
Task 2 is running
Task 3 is running
Task 4 is running
Task 0 is completed
Task 5 is running
Task 1 is completed
Task 4 is completed
Task 7 is running
Task 3 is completed
Task 8 is running
Task 2 is completed
Task 9 is running
Task 6 is running
Task 5 is completed
Task 7 is completed
Task 9 is completed
Task 8 is completed
Task 6 is completed
executeServiceAwaitTermination Finished All Tasks...

executorService.invokeAll

使用invokeAll提交所有任務,代碼如下:

private static void executeServiceInvokeAll() {
  ExecutorService executorService = Executors.newFixedThreadPool(THREADS);
  List<Callable<Void>> tasks = new ArrayList<>();

  IntStream.range(0, NUM)
    .forEach(i -> tasks.add(new PkslowTask("Task " + i)));

  try {
    executorService.invokeAll(tasks);
  } catch (InterruptedException e) {
    throw new RuntimeException(e);
  }

  executorService.shutdown();
  System.out.println("executeServiceInvokeAll Finished All Tasks...");
}

結果:

Task 1 is running
Task 2 is running
Task 0 is running
Task 3 is running
Task 4 is running
Task 1 is completed
Task 3 is completed
Task 0 is completed
Task 2 is completed
Task 4 is completed
Task 8 is running
Task 5 is running
Task 6 is running
Task 9 is running
Task 7 is running
Task 8 is completed
Task 5 is completed
Task 6 is completed
Task 9 is completed
Task 7 is completed
executeServiceInvokeAll Finished All Tasks...

ExecutorCompletionService

ExecutorCompletionService通過take()方法,會返回最早完成的任務,代碼如下:

private static void executorCompletionService() {
  ExecutorService executorService = Executors.newFixedThreadPool(10);
  CompletionService<String> service = new ExecutorCompletionService<>(executorService);

  List<Callable<String>> callables = new ArrayList<>();
  callables.add(new DelayedCallable(2000, "2000ms"));
  callables.add(new DelayedCallable(1500, "1500ms"));
  callables.add(new DelayedCallable(6000, "6000ms"));
  callables.add(new DelayedCallable(2500, "2500ms"));
  callables.add(new DelayedCallable(300, "300ms"));
  callables.add(new DelayedCallable(3000, "3000ms"));
  callables.add(new DelayedCallable(1100, "1100ms"));
  callables.add(new DelayedCallable(100, "100ms"));
  callables.add(new DelayedCallable(100, "100ms"));
  callables.add(new DelayedCallable(100, "100ms"));

  callables.forEach(service::submit);

  for (int i = 0; i < NUM; i++) {
    try {
      Future<String> future = service.take();
      System.out.println(future.get() + " task is completed");
    } catch (InterruptedException | ExecutionException e) {
      throw new RuntimeException(e);
    }
  }

  System.out.println("executorCompletionService Finished All Tasks...");

  executorService.shutdown();
  awaitTerminationAfterShutdown(executorService);
}

這裡不同任務的時長是不一樣的,但會先返回最早完成的任務:

2000ms is running
2500ms is running
300ms is running
1500ms is running
6000ms is running
3000ms is running
1100ms is running
100ms is running
100ms is running
100ms is running
100ms is completed
100ms is completed
100ms task is completed
100ms task is completed
100ms is completed
100ms task is completed
300ms is completed
300ms task is completed
1100ms is completed
1100ms task is completed
1500ms is completed
1500ms task is completed
2000ms is completed
2000ms task is completed
2500ms is completed
2500ms task is completed
3000ms is completed
3000ms task is completed
6000ms is completed
6000ms task is completed
executorCompletionService Finished All Tasks...

代碼

代碼請看GitHub: https://github.com/LarryDpk/pkslow-samples


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • ##一、通訊錄準備 #####1. 通訊錄信息的準備 #####2. 通訊錄功能的框架 #####3. 文件安排 ##二、實現通訊錄的功能 #####1. 添加功能 #####2. 刪除功能 #####3. 展示功能 #####4. 更改功能 #####5. 查找功能 #####6. 排序功能 ## ...
  • C++中的仿函數(function object)是一個重載了函數調用運算符(operator())的類或結構體,在使用時可以像函數一樣調用。通過仿函數,C++程式員可以更加靈活地實現自己的演算法。 ...
  • 緩存的重要性 簡而言之,緩存的原理就是利用空間來換取時間。通過將數據存到訪問速度更快的空間里以便下一次訪問時直接從空間里獲取,從而節省時間。 我們以CPU的緩存體係為例: CPU緩存體系是多層級的。分成了CPU -> L1 -> L2 -> L3 -> 主存。我們可以得到以下啟示。 越頻繁使用的數據 ...
  • 前言: Servlet 容器初始化 Servlet 時,會為這個 Servlet 創建一個 ServletConfig 對象,並將 ServletConfig 對象作為參數傳遞給 Servlet 。通過 ServletConfig 對象即可獲得當前 Servlet 的初始化參數信息。一個 Web 應 ...
  • Tread多線程 什麼是線程? 線程(Thread)是一個程式內部的一條執行流程。 程式中如果只有一條執行流程,那這個程式就是單線程的程式。 多線程是什麼? 多線程是指從軟硬體上實現的多條執行流程的技術(多條線程由cpu負責調度執行)。 多線程的創建方式 方式一:繼承Thread ①定義一個子類My ...
  • python的基本認識 初識python: python是一種跨平臺的、開源的、免費的、解釋型的高級編程語言; python的應用領域十分廣泛、如web編程、圖像處理、黑客編程、網路爬蟲和科學計算等; python學習簡單、開發速度快、節省時間和精力。 python具有豐富和強大的庫,能夠把用其他語 ...
  • 昨天木子問我能不能做自動刷某音短視頻,還要自動刷小哥哥,不是小哥哥就划走。 我心想,這女人真麻煩,怎麼這麼多事。 不好好工作天天想著小哥哥! 為了不得罪她,當時我就先答應了下來,然而實際上我把小哥哥變成了小姐姐,刷什麼小哥哥,多沒品味! 好了,話不多說,我們直接上代碼! 代碼實戰 首先導入需要使用的 ...
  • 前言 每次啟動SpringBoot項目時,總是能看到控制台列印了一串字元,隱約能辨認出是“Spring”,不知大家是否也好奇過是怎麼實現的,是直接列印固定的字元串,還是根據什麼演算法去生成的?於是閑暇無事,探究一番。 只想修改banner可以跳到文末查看 SpringBoot是怎麼列印的 Banner ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...