首先我想做的是:在主線程執行期間,我想暫停主線程并啟動兩個并行線程。一旦這兩個并行線程終止,我想再次從主線程開始。我嘗試過的: ... ... 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
您可能想為此示例添加更多/一些異常處理。但它應該讓我們了解這是如何運作的。

慕碼人2483693
TA貢獻1860條經驗 獲得超9個贊
您可以考慮使用 Java?CompletableFuture來實現該目標。
使用其諸如SupplyAsync或runAsync之類的函數,您可以啟動子線程并最終連接它們各自的結果?;蛘吣梢院唵蔚刈屩骶€程等待,直到后續線程完成。
最近,我設法使用同一個類實現了一個示例分散-聚集函數。
添加回答
舉報
0/150
提交
取消