CountDownLatch
CountDownLatch#tryAcquireShared
protected int tryAcquireShared(int acquires) {
return (getState() == 0) ? 1 : -1; //获取状态是不是达到条件
}
CountDownLatch#tryReleaseShared
protected boolean tryReleaseShared(int releases) {
// Decrement count; signal when transition to zero
for (;;) {
int c = getState(); //获取状态
if (c == 0) //表示已达到条件
return false;
int nextc = c-1;
if (compareAndSetState(c, nextc)) //循环cas操作释放资源
return nextc == 0; //如果为true 需要唤醒等待的await节点
}
}
CyclicBarrier
CyclicBarrier#dowait
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(); //唤醒条件等待队列,设置broken = true 重置资源数量
throw new InterruptedException();
}
int index = --count; //如果为0,则开启栅栏
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();
}
}
//如果index >0
// 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
return index;
if (timed && nanos <= 0L) { //超过了时间限制,则抛出异常
breakBarrier();
throw new TimeoutException();
}
}
} finally {
lock.unlock();
}
}