CyclicBarrier
實現所有線程都到達某一點之後開始執行
初始化
private static class Generation {
// 爲 true 的情況
// 1. 超時
// 2. 被中斷
// 3. 運行拋出異常
// 4. 被重置
boolean broken = false;
}
private final ReentrantLock lock = new ReentrantLock();
private final Condition trip = lock.newCondition();
private final int parties;
// 當 count 減少到 0 的時候。
private final Runnable barrierCommand;
private Generation generation = new Generation();
// 總數
private int count;
await
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;
// 執行hook
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();
// 設置了超時,等待 nanos 納秒
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();
}
}
// reset() 或 中斷
if (g.broken)
throw new BrokenBarrierException();
// reset() 或 count 爲 0
if (g != generation)
return index;
// 超時
if (timed && nanos <= 0L) {
breakBarrier();
throw new TimeoutException();
}
}
} finally {
lock.unlock();
}
}
其他函數都很簡單,沒分析的必要
總結
CyclicBarrier 整個實現還是比較好理解的。有鎖的基本知識即可。