循环栅栏适用的场景同计数器类似,差别在于计数器更适合某个线程等待多个线程到达某个状态(countDown)的场景,而循环栅栏更适合多个线程共同等待某个预设的状态(count == 0),到达状态后每个线程再继续执行各自的任务。这里举一个生活中的例子,比如公司举办运动会招募了10名志愿者,每个志愿者要要做什么由一个组织者 A 来进行安排,A 通知大家第二天9点在公司集合,到齐之后安排工作。于是 A 8:30来到公司等待志愿者到齐开始安排任务,此时 A 的等待就适合使用计数器。运动会上有一项田径比赛,一共有5名选手参赛,先到的选手需要等待未到的选手就位,比赛才能开始进行,此时选手之间的等待就适合使用循环栅栏。
1. CyclicBarrier()
public CyclicBarrier(int parties) {
this(parties, null);
}
public CyclicBarrier(int parties, Runnable barrierAction) {
if (parties <= 0) throw new IllegalArgumentException();
this.parties = parties;
this.count = parties;
this.barrierCommand = barrierAction;
}
2. await()
public int await() throws InterruptedException, BrokenBarrierException {
try {
return dowait(false, 0L);
} catch (TimeoutException toe) {
throw new Error(toe); // cannot happen
}
}
dowait()
private int dowait(boolean timed, long nanos)
throws InterruptedException, BrokenBarrierException,
TimeoutException {
final ReentrantLock lock = this.lock;
lock.lock();
try {
final Generation g = generation;
if (g.broken)
throw new BrokenBarrierException();
// 如果当前线程被中断过,将 barrier 的状态重置并唤醒所有等待中的线程
if (Thread.interrupted()) {
// 将 barrier 的状态重置并唤醒所有当前 generation 下阻塞中的线程
breakBarrier();
throw new InterruptedException();
}
int index = --count;
if (index == 0) { // tripped
boolean ranAction = false;
try {
// barrierCommand 来自实例化 CyclicBarrier 时传入的任务
final Runnable command = barrierCommand;
if (command != null)
command.run();
ranAction = true;
// 重置 barrier 至初始状态,以便下一轮使用,这也是 CyclicBarrier 可循环使用的实现
// 每次到达栅栏后,会产生下一代
nextGeneration();
return 0;
} finally {
// 任务未执行成功,也会将 barrier 的状态重置并唤醒所有当前 generation 下阻塞中的线程
if (!ranAction)
breakBarrier();
}
}
// loop until tripped, broken, interrupted, or timed out
for (;;) {
try {
// 不需要超时判断,直接将当前线程加入等待队列,直到最后一个加入的线程执行 int index = --count; 后将计数器清零;
// 进而执行 nextGeneration(); 方法将所有等待队列中的线程唤醒
if (!timed)
trip.await();
else if (nanos > 0L)
nanos = trip.awaitNanos(nanos);
} catch (InterruptedException ie) {
if (g == generation && ! g.broken) {
breakBarrier();
throw ie;
} else {
// We're about to finish waiting even if we had not
// been interrupted, so this interrupt is deemed to
// "belong" to subsequent execution.
Thread.currentThread().interrupt();
}
}
if (g.broken)
throw new BrokenBarrierException();
if (g != generation)
return index;
if (timed && nanos <= 0L) {
breakBarrier();
throw new TimeoutException();
}
}
} finally {
lock.unlock();
}
}
breakBarrier()
private void breakBarrier() {
generation.broken = true;
count = parties;
// 唤醒最后一代里等待队列中的线程
trip.signalAll();
}
nextGeneration()
private void nextGeneration() {
// signal completion of last generation
// 唤醒最后一代里等待队列中的线程
trip.signalAll();
// set up next generation
// 重置 barrier
count = parties;
generation = new Generation();
}
3. reset()
public void reset() {
final ReentrantLock lock = this.lock;
lock.lock();
try {
// 中断当前的一代
breakBarrier(); // break the current generation
// 进入下一代
nextGeneration(); // start a new generation
} finally {
lock.unlock();
}
}