例子
public static void main(String[] args) throws InterruptedException {
CountDownLatch countDownLatch = new CountDownLatch(3);
for (int i=0; i<3; i++) {
new Thread(() -> {
System.out.println("线程: " + Thread.currentThread().getName() + "开始执行");
countDownLatch.countDown();
System.out.println("线程: " + Thread.currentThread().getName() + "执行结束");
}).start();
}
System.out.println("hahaha");
countDownLatch.await();
System.out.println("shutdown");
}
countDownLatch会将线程阻塞在await语句那里,直到count计数为0,然后往后执行
源码分析
public class CountDownLatch {
//同步器
private final Sync sync;
//构造方法 传入一个计数
public CountDownLatch(int count) {
if (count < 0) throw new IllegalArgumentException("count < 0");
this.sync = new Sync(count);
}
//同步器 静态内部类 继承aqs
private static final class Sync extends AbstractQueuedSynchronizer {
//传入计数,设置到aqs的state
Sync(int count) {
setState(count);
}
//获取计数
int getCount() {
return getState();
}
//获取共享锁
protected int tryAcquireShared(int acquires) {
return (getState() == 0) ? 1 : -1;
}
//释放共享锁
protected boolean tryReleaseShared(int releases) {
for (;;) {
int c = getState();
if (c == 0)
return false;
int nextc = c-1;
if (compareAndSetState(c, nextc))
return nextc == 0;
}
}
}
//await方法,将线程阻塞
public void await() throws InterruptedException {
sync.acquireSharedInterruptibly(1);
}
//将计数减一
public void countDown() {
sync.releaseShared(1);
}
}
public abstract class AbstractQueuedSynchronizer
extends AbstractOwnableSynchronizer
implements java.io.Serializable {
//共享锁中断
public final void acquireSharedInterruptibly(int arg)
throws InterruptedException {
if (Thread.interrupted())
throw new InterruptedException();
//count计数不为0时 计数为0,await放开,执行await之后的逻辑
if (tryAcquireShared(arg) < 0)
doAcquireSharedInterruptibly(arg);
}
private void doAcquireSharedInterruptibly(int arg)
throws InterruptedException {
//将一个共享锁节点放入aqs队列
final Node node = addWaiter(Node.SHARED);
boolean failed = true;
try {
for (;;) {
final Node p = node.predecessor();
if (p == head) {
int r = tryAcquireShared(arg);
//count计数为0时
if (r >= 0) {
setHeadAndPropagate(node, r);
p.next = null; // help GC
failed = false;
return;
}
}
//count计数不为0时,挂起线程,和上一篇reentrentLock一样的方法
if (shouldParkAfterFailedAcquire(p, node) &&
parkAndCheckInterrupt())
throw new InterruptedException();
}
} finally {
if (failed)
cancelAcquire(node);
}
}
private void setHeadAndPropagate(Node node, int propagate) {
Node h = head;
setHead(node);
//propagate > 0 当前计数为0
if (propagate > 0 || h == null || h.waitStatus < 0 ||
(h = head) == null || h.waitStatus < 0) {
Node s = node.next;
if (s == null || s.isShared())
doReleaseShared();
}
}
//
public final boolean releaseShared(int arg) {
//当前计数为0
if (tryReleaseShared(arg)) {
doReleaseShared();
return true;
}
return false;
}
//释放 循环将aqs队列中的所有共享锁一次性全部释放,aqs队列中的共享锁都出来执行其逻辑
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
unparkSuccessor(h);
}
else if (ws == 0 &&
!compareAndSetWaitStatus(h, 0, Node.PROPAGATE))
continue; // loop on failed CAS
}
if (h == head) // loop if head changed
break;
}
}
}