CyclicBarrier:循环屏障,作用是用于多个线程执行到某一处逻辑时阻塞,当最后一个线程到达时在同步唤醒,可用于并发执行后的统计计算等等。此处就不介绍用法了。
先看构造方法
public CyclicBarrier(int parties, Runnable barrierAction) {
if (parties <= 0) throw new IllegalArgumentException();
this.parties = parties;
this.count = parties;
this.barrierCommand = barrierAction;
}
一个变量值,用于当线程执行wait时自减,barrierCommand ,当count 减至0时,需要执行的代码逻辑。
我们只需要关心一个核心方法
dowait(boolean timed, long nanos);
dowait方法我们可以拆成两个部分来看
第一部分index自减后不为0的情况,此时会执行这段逻辑
// loop until tripped, broken, interrupted, or timed out
for (;;) {
try {
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();
}
}
}
trip.await();其实就是同步队列转条件队列,释放锁,并阻塞当前线程的一个过程
public final void await() throws InterruptedException {
if (Thread.interrupted())
throw new InterruptedException();
//加入条件队列中
Node node = addConditionWaiter();
//释放锁
int savedState = fullyRelease(node);
int interruptMode = 0;
while (!isOnSyncQueue(node)) {
//阻塞当前线程
LockSupport.park(this);
if ((interruptMode = checkInterruptWhileWaiting(node)) != 0)
break;
}
//被唤醒后会再次获取同步队列中的锁
if (acquireQueued(node, savedState) && interruptMode != THROW_IE)
interruptMode = REINTERRUPT;
if (node.nextWaiter != null) // clean up if cancelled
unlinkCancelledWaiters();
if (interruptMode != 0)
reportInterruptAfterWait(interruptMode);
}
当index减至0时,执行command方法并执行nextGeneration();
内部逻辑为rip.signalAll();这个方法主要是唤醒条队列中的线程
后续会执行count = parties;给count赋予初值,这里代表CyclicBarrier是可以循环使用的 这也是和countdownLunch最大的区别
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();
if (Thread.interrupted()) {
breakBarrier();
throw new InterruptedException();
}
int index = --count;
if (index == 0) { // tripped
boolean ranAction = false;
try {
final Runnable command = barrierCommand;
if (command != null)
//执行command方法
command.run();
ranAction = true;
//唤醒条件队列中的线程,让他们去竞争ReentrantLock中同步队列的锁
nextGeneration();
return 0;
} finally {
if (!ranAction)
breakBarrier();
}
}