用法我就不说了,百度一大堆,我在这里带大家看看源码了解其原理:
CyclicBarrier barrier = new CyclicBarrier(3);
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 和 parties 一开始都是初始值。
接着了解其核心方法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) //判断线程是否被破坏,其实就是下面breakBarrier()方法会设置为被中断
throw new BrokenBarrierException();
if (Thread.interrupted()) {
breakBarrier();//设置线程中断
throw new InterruptedException();
}
int index = --count;重头戏在这里,判断之前声明的count是否降到0,所有的线程都走到这里的话就会减到0
if (index == 0) { // tripped
boolean ranAction = false; 设置一个标识,
try {
final Runnable command = barrierCommand;
if (command != null)
command.run();自己先跑
ranAction = true;
nextGeneration();唤醒其他线程跑,并且设置count 为原来的值,就是又可以循环使用了
return 0;return 之前执行finally lock.unlock();方法释放锁。
}
} 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();
}
}
大概这些逻辑,我们理解理清楚了,大概就是声明了一个数字 count ,然后每次调用await()就会减1 并且判断是否到0了,如果到了就自己先跑并且唤醒其他线程。并且重新设置count的值。从而实现可循环。