CyclicBarrier
说了CountDownlatch就不得不说下CyclicBarrier,它们俩的功能是大同小异的。CyclicBarrier被称为同步屏障,它可以使一定数量的线程反复在屏障处汇集,当线程到达屏障处调用await方法,该线程就会在此处阻塞,直到所有线程都达到屏障,那么屏障就会打开,所有线程就会继续执行任务
基本结构
该类有几个成员变量:
private static class Generation {
boolean broken = false;
}
// 保护屏障用的锁,操作count、generation等成员变量时
private final ReentrantLock lock = new ReentrantLock();
// 到达屏障并且不能放行的线程会在trip上等待
private final Condition trip = lock.newCondition();
// 打破一次屏障需要多少线程,该变量是在初始化时赋值的
private final int parties;
// 回调任务
private final Runnable barrierCommand;
// 代表当前屏障
private Generation generation = new Generation();
// 还剩多少线程可以打破屏障,该值初始化和partition一样
private int count;
打破屏障的条件
除了当所有线程都到达屏障处可以打破屏障外,以下情况也有可能会打破屏障,并可能会抛出异常:
- 其他某个线程中断当前线程
- 其他某个线程中断其他正在等待的线程
- 其他线程调用了reset方法
- 其他屏障在等待时超时
- 最后一个线程在执行回调任务时发生异常
await
当一个线程到达屏障处时会调用一次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();
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 {
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进行加锁,并把当前屏障赋值给g
- 如果当前屏障被破坏,抛出BrokenBarrierException异常
- 如果当前线程被中断,破坏当前屏障并抛出InterruptedException异常
- --count并赋值给index,代表的是当前线程已经进入屏障,index表示到达当前线程的索引
- 如果index等于0,表达该线程是最后一个线程
- 设置任务执行结果为false
- 如果回调任务command不为null,执行回调任务
- 设置任务执行结果为true
- 调用nextGeneration重置屏障,唤醒其他所有线程
- 返回0
- 进入finally模块,如果任务执行结果为false,那么就会执行finally代码块中的breakBarrier方法,破坏屏障
- 如果index不等于0,表示该线程不是最后一个线程,进入死循环
- 如果不是超时等待,则调用trip.await()方法,将当前线程放入等待队列中
- 如果是超时等待,则调用trip.awaitNanos方法,将当前线程放入等待队列中,该方法会有超时时间的限制
- 如果当前线程被破坏,抛出异常
- 如果g和当前屏障不相等,直接返回index
- 如果是超时等待并且超时时间小于等于0了,那么就破坏屏障并抛出异常

浙公网安备 33010602011771号