gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 01:44:28 25 4
gpt4 key购买 nike

首先我想做的是:

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

我尝试过:

    ...
...
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 一切都会停止并且主线程永远不会重新启动。 (我在连接后放置了一个断点,以查看主线程何时重新启动)。

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

谢谢

戴维德

最佳答案

正如评论中提到的,我还建议使用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

您可能想为此示例添加更多/一些异常处理。但它应该能让您了解这是如何运作的。

关于java - 主线程等待两个并行子线程java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58640303/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com