java.util.concurrent.CyclicBarrier
CyclicBarrier是一个同步辅助类,允许一组线程互相等待,直到到达某个公共屏障点 (common barrier point)。因为该 barrier 在释放等待线程后可以重用,所以称它为循环 的 barrier。
CountDownLatch和CyclicBarrier的区别
(01) CountDownLatch的作用是允许1或N个线程等待其他线程完成执行;而CyclicBarrier则是允许N个线程相互等待。
(02) CountDownLatch的计数器无法被重置;CyclicBarrier的计数器可以被重置后使用,因此它被称为是循环的barrier。
1.类变量&常量
//一个可重入锁,CyclicBarrier的主要加锁方式
private final ReentrantLock lock = new ReentrantLock();
//等待条件
private final Condition trip = lock.newCondition();
//同时到达barrier的线程数
private final int parties;
//当满足条件时,即栅栏开放后运行的task
private final Runnable barrierCommand;
private Generation generation = new Generation();
//处于等待状态的线程数
private int count;
2.构造方法
//只有线程数,没有task,表示到达barrier后什么也不做
public CyclicBarrier(int parties) {
this(parties, null);
}
//同时到达barrier的线程数,和到达之后运行的另外一个线程
public CyclicBarrier(int parties, Runnable barrierAction) {
if (parties <= 0) throw new IllegalArgumentException();
this.parties = parties;
this.count = parties;
this.barrierCommand = barrierAction;
}
3.内部类
内部类Generation的作用是CyclicBarrier的一个成员遍历
private static class Generation {
boolean broken = false;
}
4.重要方法
1. await方法
//无参await方法,用于等待,直到所有的线程均到达barrier
public int await() throws InterruptedException, BrokenBarrierException {
try {
return dowait(false, 0L);
} catch (TimeoutException toe) {
throw new Error(toe); // cannot happen
}
}
//有等待时长的await方法,最多等待timeout的时间
public int await(long timeout, TimeUnit unit)
throws InterruptedException,
BrokenBarrierException,
TimeoutException {
return dowait(true, unit.toNanos(timeout));
}
2.breakBarrier方法,将Barrier移除,并通知所有线程。一般当线程被中断时调用
private void breakBarrier() {
generation.broken = true;
count = parties; //因为在doWait中,count会一直减,故需要重新赋值
trip.signalAll();
}
3. getNumberWaiting方法,获取当前的正在等待的线程数
public int getNumberWaiting() {
final ReentrantLock lock = this.lock;
lock.lock();
try {
return parties - count;
} finally {
lock.unlock();
}
}
4. nextGeneration用于换代操作。同一批的线程属于同一代,即同一个Generation。
这样可以实现重复使用栅栏。
private void nextGeneration() {
// signal completion of last generation
trip.signalAll();
// set up next generation
count = parties;
generation = new Generation();
}
5. isBroken方法,判断当前栅栏是否被打开
public boolean isBroken() {
final ReentrantLock lock = this.lock;
lock.lock();
try {
return generation.broken;
} finally {
lock.unlock();
}
}
6.reset方法,当一批线程通过栅栏后,通过reset方法,将栅栏reset,用于循环使用
public void reset() {
final ReentrantLock lock = this.lock;
lock.lock();
try {
breakBarrier(); // break the current generation
nextGeneration(); // start a new generation
} finally {
lock.unlock();
}
}
7.doWait方法,CyclicBarrier的核心方法
private int dowait(boolean timed, long nanos)
throws InterruptedException, BrokenBarrierException,
TimeoutException {
final ReentrantLock lock = this.lock;
lock.lock();
try {
final Generation g = generation; //保存当前的generation
if (g.broken)
throw new BrokenBarrierException();
if (Thread.interrupted()) {//若发生线程中断,则破坏栅栏,唤醒所有的等待线程
breakBarrier();
throw new InterruptedException();
}
int index = --count;
//index=0,表示有parties个线程到达barrier,此时可以执行后续的task
if (index == 0) {
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 {
//是否为超时等待,若是则用await方法,否则调用awaitNanos方法
if (!timed)
trip.await();
else if (nanos > 0L)
nanos = trip.awaitNanos(nanos);
} catch (InterruptedException ie) {
if (g == generation && ! g.broken) {
breakBarrier();
throw ie;
} else {
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(); //释放锁
}
}