主线程等待两个并行线程子 java

Main thread to wait two parallel threads children java

首先我想做的是:

在主线程执行期间,我想暂停主线程并启动两个并行线程。一旦这两个并行线程终止,我想从主线程重新开始。

我尝试了什么:

    ...
    ...
    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)
...

线程生成器自定义 class

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之后打了个断点,看主线程什么时候重启)。

也许这些概念有点混乱,而且我不确定我是否需要同时使用屏障和连接,或者只是其中一种技术。

谢谢

大卫

您可以考虑使用 Java CompletableFuture 来实现 objective.

使用 supplyAsyncrunAsync 等功能,您可以启动子线程并在最后加入它们各自的结果。或者您可以简单地让主线程等待,直到后续线程完成。

最近我设法使用相同的 class.

实现了一个示例分散-聚集函数

查看 Java 文档以获取更多产品并找到最佳可用功能:https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/CompletableFuture.html

如评论中所述,我还建议使用 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

您可能希望向此示例添加 more/some 异常处理。但它应该让您了解这是如何工作的。