简单示例
public class CyclicBarrierTest {
public static void main(String[] args) {
CyclicBarrier cb = new CyclicBarrier(2, () -> {
System.out.println("即将打破屏障");
});
for (int i = 0; i < 2; i++) {
new Thread(() -> {
System.out.println(Thread.currentThread().getName() + "开始运行");
try {
cb.await();
System.out.println(Thread.currentThread().getName() + "已经穿越了第1个屏障");
cb.await();
System.out.println(Thread.currentThread().getName() + "已经穿越了第2个屏障");
} catch (InterruptedException | BrokenBarrierException e) {
e.printStackTrace();
}
}).start();
}
}
}
运行结果:
Thread-0开始运行
Thread-1开始运行
即将打破屏障
Thread-1已经穿越了第1个屏障
Thread-0已经穿越了第1个屏障
即将打破屏障
Thread-0已经穿越了第2个屏障
Thread-1已经穿越了第2个屏障
源码分析
构造方法
public CyclicBarrier(int parties, Runnable barrierAction) {
if (parties <= 0) throw new IllegalArgumentException();
this.parties = parties;
this.count = parties;
this.barrierCommand = barrierAction;
}
await()
- 将计数器减1,如果计数器不等于0,执行
trip.await();
,进行阻塞;如果计数器等于0,执行command,唤醒线程。
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 {
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();
}
}
CyclicBarrier#nextGeneration
,唤醒阻塞线程。
private void nextGeneration() {
// signal completion of last generation
trip.signalAll();
// set up next generation
count = parties;
generation = new Generation();
}
CountDownLatch和CyclicBarrier的区别
CountDownLatch
,是一个线程或多个线程等待另外多个线程执行完毕之后才执行。内部维护一个计数器,每个线程调用一次countDown
后,计数器减1,计数器减为0后,会唤醒因调用await()而阻塞的线程。
CyclicBarrier
,多个线程互相等待,直到所有的线程都达到屏障点,才可以一起接着执行。同样可以理解为内部有一个可重置的计数器,每个线程调用await()后,计数器减1,若计数器的值不为0,将会阻塞该线程。当最后一个线程调用await()后,计数器为0,将会唤醒所有阻塞的线程,并开启下一代,重置此计数器的值。