CyclicBarrier
它允许一组线程互相等待,知道到达某个公共屏障点。barrier在释放等待线程后可以重用。
CyclicBarrier的内部是使用重入锁ReentrantLock和Condition。
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;
}
parties表示拦截线程的数量。
barrierAction为CyclicBarrier接受的Runnable命令,用于在线程到达屏障时,优先执行barrierAction,用于处理更加复杂的业务场景。
await
public int await() throws InterruptedException, BrokenBarrierException {
try {
return dowait(false, 0L);
} catch (TimeoutException toe) {
throw new Error(toe); // cannot happen
}
}
await()方法内部调用dowait()方法
private int dowait(boolean timed, long nanos)
throws InterruptedException, BrokenBarrierException,
TimeoutException {
final ReentrantLock lock = this.lock;
lock.lock();
try {
//分代
final Generation g = generation;
//当前generation“已损坏“,抛出BrokenBarrierException
if (g.broken)
throw new BrokenBarrierException();
//如果线程中断,终止CyclicBarrier
if (Thread.interrupted()) {
breakBarrier();
throw new InterruptedException();
}
//如果count==0,表示所有线程都已经到barrier,触发Runnable任务
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();
}
}
如果该线程不是到达的最后一个线程,则他会一直处于等待状态,除非发生以下情况:
1.最后一个线程到达,即index == 0
2.超出了指定时间(超时等待)
3.其他的某个线程中断当前线程
4.其他的某个线程中断另一个等待的线程
5.其他的某个线程在等待barrier超时
6.其他的某个线程在此barrier调用reset()方法。reset()方法用于将屏障重置为初始状态
适用场景
用于多线程计算数据,最后合并计算结果的场景