首先我想做的是:
在主线程执行期间,我想暂停主线程并启动两个并行线程。一旦这两个并行线程终止,我想从主线程重新开始。
我尝试了什么:
...
...
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
}
目前尚不清楚这里发生了什么,但它肯定不起作用。一旦我调用加入,一切都会停止,主线程永远不会重新启动。(我在连接之后放置了一个断点,以查看主线程何时重新启动)。
也许这些概念有点混乱,而且我不确定我是否需要同时使用屏障和连接,或者只是其中一种技术。
谢谢
戴维德