CyclicBarrier
作用
让一组线程等待某个事件(barrier)的发生。
实现原理
在 dowait
方法中有如下计数器:
int index = --count;
if (index == 0) { // tripped
boolean ranAction = false;
try {
final Runnable command = barrierCommand;
if (command != null)
command.run();
ranAction = true;
nextGeneration();
return 0;
} finally {
if (!ranAction)
breakBarrier();
}
}
其中 runGeneration
或 breakBarrier
中有如下代码片段:
trip.signalAll();
trip
是信号量:
/** Condition to wait on until tripped */
private final Condition trip = lock.newCondition();