CountDownLatch使用场景:
通常使用于多个线程异步执行,之后希望将返回结果转为同步处理,可以说是起到多个线程间的通信。
基于源码进行分析:
CountDownLatch有一下几个方法:
public CountDownLatch(int count) {
if (count < 0) throw new IllegalArgumentException("count < 0");
this.sync = new Sync(count);
}
方法中count为传入的并发线程待执行个数,执行Sync(count),初始化AbstractQueuedSynchronizer中state值,作为统计个数
Sync(int count) {
setState(count);
}
执行过程中会调用wait()方法,对以下执行过程进行解释。
public void await() throws InterruptedException {
sync.acquireSharedInterruptibly(1);
}
public final void acquireSharedInterruptibly(int arg)
throws InterruptedException {
if (Thread.interrupted())
throw new InterruptedException();
if (tryAcquireShared(arg) < 0)
doAcquireSharedInterruptibly(arg);
}
private void doAcquireSharedInterruptibly(int arg)
throws InterruptedException {
final Node node = addWaiter(Node.SHARED);
boolean failed = true;
try {
for (;;) {
final Node p = node.predecessor();
if (p == head) {
int r = tryAcquireShared(arg);
if (r >= 0) {
setHeadAndPropagate(node, r);
p.next = null; // help GC
failed = false;
return;
}
}
if (shouldParkAfterFailedAcquire(p, node) &&
parkAndCheckInterrupt())
throw new InterruptedException();
}
} finally {
if (failed)
cancelAcquire(node);
}
}
protected int tryAcquireShared(int acquires) {
return (getState() == 0) ? 1 : -1;
}
以上执行顺序中doAcquireSharedInterruptibly()方法,会获取tryAcquireShared()返回值,tryAcquireShared比较的是当前线程未执行完毕的个数,只有当线程全部执行完毕时,tryAcquireShared返回1,才会退出循环,否则阻塞在for循环中。
中间的参数state即待执行线程个数,通过调用coutDown()方法进行修改,每个线程在执行完毕时调用。
public void countDown() {
sync.releaseShared(1);
}
public final boolean releaseShared(int arg) {
if (tryReleaseShared(arg)) {
doReleaseShared();
return true;
}
return false;
}
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))
return nextc == 0;
}
}
tryReleaseShared方法会获取当前state进行修改,当所有线程执行完毕时,state值为0,触发doAcquireSharedInterruptibly中循环,int r = tryAcquireShared(arg);r为1,进入if判断,退出循环,释放锁。if判断内容为AQS相关知识,就不详述了,有兴趣可以自行学习。CountDownLatch是AQS的一种实现,有兴趣的再看AQS。
本文梳理CountDownLatch执行流程,具体细节可以自行学习。