一.使用
1个线程等待多个线程执行完成后再执行。
public class CountDownLatch1 {
public static void main(String[] args) throws InterruptedException {
CountDownLatch countDownLatch = new CountDownLatch(5);
for (int i = 0; i < 5; i++) {
new Thread(new Runnable() {
@SneakyThrows
@Override
public void run() {
Thread.sleep(3000);
System.out.println("countDown");
countDownLatch.countDown();
}
}).start();
}
System.out.println("await");
countDownLatch.await();
System.out.println("---------------");
}
}
输出:
await
countDown
countDown
countDown
countDown
countDown
---------------
多个线程等待1个线程执行完成后再执行。
public class CountDownLatch2 {
public static void main(String[] args) throws InterruptedException {
CountDownLatch countDownLatch = new CountDownLatch(1);
for (int i = 0; i < 5; i++) {
new Thread(new Runnable() {
@SneakyThrows
@Override
public void run() {
System.out.println("await");
countDownLatch.await();
System.out.println("hello");
}
}).start();
}
Thread.sleep(3000);
System.out.println("countDown");
countDownLatch.countDown();
}
}
输出:
await
await
await
await
await
countDown
hello
hello
hello
hello
hello
二.源码
1.构造函数
public CountDownLatch(int count) {
this.sync = new Sync(count);
}
private static final class Sync extends AbstractQueuedSynchronizer {
Sync(int count) {
setState(count);
}
}
2.await
public void await() throws InterruptedException {
sync.acquireSharedInterruptibly(1);
}
public final void acquireSharedInterruptibly(int arg)
throws InterruptedException {
// 初始时state不是0
if (tryAcquireShared(arg) < 0)
// 没拿到锁,入队阻塞
doAcquireSharedInterruptibly(arg);
}
protected int tryAcquireShared(int acquires) {
return (getState() == 0) ? 1 : -1;
}
3.countDown
public void countDown() {
sync.releaseShared(1);
}
public final boolean releaseShared(int arg) {
// state为0
if (tryReleaseShared(arg)) {
// 唤醒阻塞的线程
doReleaseShared();
return true;
}
// state不为0
return false;
}
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;
}
}