接下来就分析一下CyclicBarrier,如果有不了解CyclicBarrier的使用的话,给大家推荐一篇生动形象的入门博客:
https://blog.csdn.net/carson0408/article/details/79471490
1.构造方法。
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
}
}
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.run();
ranAction = true;
nextGeneration();
return 0;
} finally {
//job失败,那么就打破屏障
if (!ranAction)
//将generation的broken设置为true
breakBarrier();
}
}
//count 没到0
for (;;) {
try {
//timed是false
if (!timed)
//trip是condition。那么意味着,该线程暂时阻塞
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();
}
}
//从阻塞恢复之后,需要重新判断当前的状态。
//对应的阻塞唤醒是在nextGeneration()当中
if (g.broken)
throw new BrokenBarrierException();
if (g != generation)
return index;
if (timed && nanos <= 0L) {
breakBarrier();
throw new TimeoutException();
}
}
} finally {
lock.unlock();
}
}
private void nextGeneration() {
//唤醒所有的线程
trip.signalAll();
//重新赋值下一次
//从这里,可以看出parties是一个最开始保存的一个屏障数,真正操作的是count。
count = parties;
generation = new Generation();
}
3.breakBarrier()这个方法见得比较多了,那么单独拿出来看看。
private void breakBarrier() {
//将屏障打破,让其抛异常
generation.broken = true;
//还原
count = parties;
//唤醒之前等待的
trip.signalAll();
}