亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

主線程等待兩個并行子線程java

主線程等待兩個并行子線程java

慕妹3242003 2024-01-17 21:10:01
首先我想做的是:在主線程執行期間,我想暫停主線程并啟動兩個并行線程。一旦這兩個并行線程終止,我想再次從主線程開始。我嘗試過的:    ...    ...    main thread is executing    ...    ...CyclicBarrier barrier = new CyclicBarrier(2);Thread child1 = new Thread(new ThreadBuilderTask(barrier,0));Thread child2 = new Thread(new ThreadBuilderTask(barrier,1));child1.start();child2.start(); /* Now i'm expecting that child1 and child2 are running in parallel calling their fooFunction */child1.join();child2.join(); /*Now i'm expecting that main thread will wait for child1and also for child2 (that are running in parallel).*/... main thread starts again after both child1 and child2 finished (reached the await of the barrier) ... (break point set here, never reached)...線程生成器自定義類public class ThreadBuilderTask implements Runnable{    private CyclicBarrier barrier;    private int index;    ...setters and getters..    @Override    public void run() {        fooFunction(this.getIndex());        try {            this.getBarrier().await();        } catch (InterruptedException | BrokenBarrierException e) {            return;        }    }    public ThreadBuilderTask(CyclicBarrier barrier,int index){      this.barrier = barrier;      this.index = index;    }    public fooFunction(int index){        //Something taking some seconds to execute    }目前尚不清楚這里發生了什么,但它肯定不起作用。一旦我調用 join 一切都會停止并且主線程永遠不會重新啟動。(我在連接后放置了一個斷點,以查看主線程何時重新啟動)。也許這些概念有些混亂,而且我不確定是否需要同時使用屏障和連接,或者僅使用其中一種技術。
查看完整描述

2 回答

?
胡子哥哥

TA貢獻1825條經驗 獲得超6個贊

正如評論中提到的,我還建議使用CompletableFuture. 您所描述的要求的一個非?;镜氖纠赡苋缦滤荆?/p>


final Runnable runnable1 = ...;

final Runnable runnable2 = ...;


CompletableFuture<Void> future1 = CompletableFuture.runAsync(runnable1);

CompletableFuture<Void> future2 = CompletableFuture.runAsync(runnable2);


CompletableFuture.allOf(future1, future2).get(); // waits for both runnables to finish

您可能想為此示例添加更多/一些異常處理。但它應該讓我們了解這是如何運作的。


查看完整回答
反對 回復 2024-01-17
?
慕碼人2483693

TA貢獻1860條經驗 獲得超9個贊

您可以考慮使用 Java?CompletableFuture來實現該目標。

使用其諸如SupplyAsyncrunAsync之類的函數,您可以啟動子線程并最終連接它們各自的結果?;蛘吣梢院唵蔚刈屩骶€程等待,直到后續線程完成。

最近,我設法使用同一個類實現了一個示例分散-聚集函數。

查看完整回答
反對 回復 2024-01-17
  • 2 回答
  • 0 關注
  • 202 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號