第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

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

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

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

慕妹3242003 2024-01-17 21:10:01
首先我想做的是:在主線程執(zhí)行期間,我想暫停主線程并啟動兩個并行線程。一旦這兩個并行線程終止,我想再次從主線程開始。我嘗試過的:    ...    ...    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    }目前尚不清楚這里發(fā)生了什么,但它肯定不起作用。一旦我調(diào)用 join 一切都會停止并且主線程永遠不會重新啟動。(我在連接后放置了一個斷點,以查看主線程何時重新啟動)。也許這些概念有些混亂,而且我不確定是否需要同時使用屏障和連接,或者僅使用其中一種技術(shù)。
查看完整描述

2 回答

?
胡子哥哥

TA貢獻1825條經(jīng)驗 獲得超6個贊

正如評論中提到的,我還建議使用CompletableFuture. 您所描述的要求的一個非常基本的示例可能如下所示:


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

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


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

TA貢獻1860條經(jīng)驗 獲得超9個贊

您可以考慮使用 Java?CompletableFuture來實現(xiàn)該目標。

使用其諸如SupplyAsyncrunAsync之類的函數(shù),您可以啟動子線程并最終連接它們各自的結(jié)果。或者您可以簡單地讓主線程等待,直到后續(xù)線程完成。

最近,我設(shè)法使用同一個類實現(xiàn)了一個示例分散-聚集函數(shù)。

查看完整回答
反對 回復(fù) 2024-01-17
  • 2 回答
  • 0 關(guān)注
  • 188 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學習伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號