以前写过这个 https://cloud.tencent.com/developer/article/1109524
今天看CyclicBarrier源码,核心代码 这一串
/**
* Main barrier code, covering the various policies.
*/
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;//到达的线程数目 conut--
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();//等待lock上的条件 定义:private final Condition trip = lock.newCondition();
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();
}
}
一直疑惑,当一个线程获取lock.lock()锁时,什么时候释放的,要不然其他线程进来时,根本进入不了方法,怎么让int index = --count;,进而触发激活线程呢。糊涂很久,最后网上看到trip.await();解释为,等待lock上的条件(newCondition()),同时释放lock锁。这样其他线程才能获得锁,再进入dowait方法。其实,如果不用锁上的条件 (newCondition()) ,也就不好体会重入。