首先我想做的是:
在主线程执行期间,我想暂停主线程并启动两个并行线程。一旦这两个并行线程终止,我想再次从主线程开始。
我尝试过的:
...
...
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 一切都会停止并且主线程永远不会重新启动。(我在连接后放置了一个断点,以查看主线程何时重新启动)。
也许这些概念有些混乱,而且我不确定是否需要同时使用屏障和连接,或者仅使用其中一种技术。
胡子哥哥
慕码人2483693
相关分类