CountDownLatch 介绍
CountDownLatch 是用于等待线程的执行,等待线程数量为 0 后,则结束等待,执行该线程等待后所要执行的代码。
例子如下:
private static CountDownLatch caDownLatch = new CountDownLatch(2);
public static void main(String[] args) {
new Thread(){
public void run() {
System.out.println("线程" + Thread.currentThread().getName() + "开始");
System.out.println("线程" + Thread.currentThread().getName() + "等待其它两个线程执行结束");
try {
caDownLatch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("其它两个线程执行结束");
System.out.println("线程" + Thread.currentThread().getName() + "结束");
};
}.start();
new Thread(){
public void run() {
System.out.println("线程" + Thread.currentThread().getName() + "执行");
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
caDownLatch.countDown();
};
}.start();
new Thread(){
public void run() {
System.out.println("线程" + Thread.currentThread().getName() + "执行");
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
caDownLatch.countDown();
};
}.start();
}
执行结果为:
线程Thread-0开始
线程Thread-0等待其它两个线程执行结束
线程Thread-1执行
线程Thread-2执行
其它两个线程执行结束
线程Thread-0结束
CountDownLatch 源码分析
CountDownLatch 内部通过标记和阻塞线程和唤醒线程来实现功能。
首先分析 await() 方法:
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) // 如果指定等待的数量不等于 0
doAcquireSharedInterruptibly(arg);
}
private void doAcquireSharedInterruptibly(int arg)
throws InterruptedException {
// 插入该线程节点
final Node node = addWaiter(Node.SHARED);
boolean failed = true;
try {
for (;;) {
// ...
// parkAndCheckInterrupt 用于阻塞线程并判断是否被中断,内部调用 LockSupport.park 来实现
if (shouldParkAfterFailedAcquire(p, node) &&
parkAndCheckInterrupt())
throw new InterruptedException();
}
} finally {
if (failed) // 如果失败,就恢复
cancelAcquire(node);
}
}
接下来看 countDown() 方法:
public void countDown() {
sync.releaseShared(1);
}
public final boolean releaseShared(int arg) {
// tryReleaseShared 对标记减一,已经没有等待的线程时返回 true
if (tryReleaseShared(arg)) {
doReleaseShared();
return true;
}
return false;
}
private void doReleaseShared() {
for (;;) {
Node h = head;
if (h != null && h != tail) {
int ws = h.waitStatus;
if (ws == Node.SIGNAL) {
// 恢复节点状态
if (!compareAndSetWaitStatus(h, Node.SIGNAL, 0))
continue; // loop to recheck cases
// 唤醒阻塞的线程,继续执行,通过 LockSupport.unpark
unparkSuccessor(h);
}
// ...
}
// ...
}
}