Java中使用CyclicBarrier控制多个线程在执行完后,才执行后续操作,请大家帮我分析下,项目两个代码中为什么执行结果不一样:
代码1、
public class CyclicBarrierTest2 {
public static void main(String[] args) throws InterruptedException, BrokenBarrierException {
final CyclicBarrier cb = new CyclicBarrier(2, new Runnable() { // 等到线程到达后执行一个后续task
@Override
public void run() {
System.out.println("这个是最后执行吗????" + Thread.currentThread().getName() + " a");
}
});
for(int i=0; i<2; i++){
Thread r = new Thread(new Runnable() {
@Override
public void run() {
try {
cb.await();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (BrokenBarrierException e) {
e.printStackTrace();
}
System.out.println("1 " + Thread.currentThread().getName() + " a");
}
});
r.start();
}
}
}
执行结果:
这个是最后执行吗????Thread-0 a
1 Thread-1 a
1 Thread-0 a
代码2:
public class RaceConditionWithCyclicBarrier implements Callable {
static CyclicBarrier cb = null;
RaceConditionWithCyclicBarrier() {
}
/**
* @param args
* @throws Throwable
*/
public static void main(String[] args) throws Throwable {
ArrayList<Callable<Boolean>> listCall = new ArrayList<Callable<Boolean>>();
ExecutorService executor = Executors.newFixedThreadPool(2); // 必须是allThread的个数
//for(int i=0;i <1000; i++){
listCall.clear();
cb = new CyclicBarrier(2, new Runnable() { // 等到线程到达后执行一个后续task
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + "a");
}
});
listCall.add(new RaceConditionWithCyclicBarrier());
listCall.add(new RaceConditionWithCyclicBarrier());
try {
executor.invokeAll(listCall);
} catch (Throwable e) {
executor.shutdown();
throw e;
} finally {
System.out.println( " over");
}
//}
executor.shutdown();
// 这句是在所有线程都跑完之后才会执行
System.out.println("是最后吗 ");
}
@Override
public Boolean call() throws Exception {
for (int i = 0; i < 5; i++)
System.err.println("=============================== " + i);
cb.await();
return true;
}
}
执行结果:
=============================== 0
=============================== 1
=============================== 2
=============================== 3
=============================== 4
=============================== 0
=============================== 1
pool-1-thread-2a
=============================== 2
=============================== 3
=============================== 4
over
是最后吗
请高手帮我看下,为什么两个执行结果 中“是最后吗”不一样,在代码1中是开始就执行了,代码2中是最后执行的