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();
}
}

本文深入解析了CountDownLatch和CyclicBarrier两种并发控制组件的工作原理。CountDownLatch通过计数器实现线程间的同步等待,而CyclicBarrier则允许一组线程相互等待直到到达某个公共屏障点。文中详细展示了这两种组件的核心方法实现,包括CountDownLatch的tryAcquireShared和tryReleaseShared方法,以及CyclicBarrier的dowait方法。
476

被折叠的 条评论
为什么被折叠?



