CyclicBarrier介绍
CyclicBarrier字面意思回环栅栏,通过它可以实现让一组线程等待至某个状态之后再全部同时执行。叫做回环是因为当所有等待线程都被释放以后,CyclicBarrier可以被重用。我们暂且把这个状态就叫做barrier,当调用await()方法之后,线程就处于barrier了。
CyclicBarrier概览
它内部是直接使用了ReentrantLock来实现的,还有相关的Condition实现的。然后还有栅栏突破之后的通知线程方法。内部主要的实现方法是await。
源码详解
构造函数
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;
}
- count是用来标识还需要拦截多少线程的await
- 这里的parties是指循环的栅栏的拦截个数,设置进去后不会变,count循环一次到0后会重置成parties
- barrierCommand是一个Runnable接口,是用来栅栏突破后通知的
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();
}
//<1>
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();
}
}
// 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();
}
}
} finally {
lock.unlock();
}
}
- 这个方法稍微比较长了一点,我们一步步来分析
- 首先是加ReentrantLock的锁,然后是一块判断的逻辑,不清楚也并没有特别大影响,熟悉的话也比较好
- <1>部分的的逻辑是:会把count加一,然后判断是否达到了突破栅栏的条件,如果达到了就运行通知线程,然后会通过nextGeneration`,会通过lock.newCondition()的signalAll方法唤醒之前阻塞的线程,并且重置count,有兴趣可以看下nextGeneration方法,非常简单
- 剩下的那块逻辑是在引用过期时间的时候会用到,不是特别理解也没关系。
今日总结
CyclicBarrier主要通过ReentrantLock和ReentrantLock的Condition来通知阻塞线程达到目的,然后通过parties和count来重用。再来分享下我们的知识图谱: