一.使用
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@Overridepublic void run() {Thread.sleep(3000);System.out.println("countDown");countDownLatch.countDown();}}).start();}System.out.println("await");countDownLatch.await();System.out.println("---------------");}}输出:awaitcountDowncountDowncountDowncountDowncountDown---------------
多个线程等待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@Overridepublic void run() {System.out.println("await");countDownLatch.await();System.out.println("hello");}}).start();}Thread.sleep(3000);System.out.println("countDown");countDownLatch.countDown();}}输出:awaitawaitawaitawaitawaitcountDownhellohellohellohellohello
二.源码
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不是0if (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为0if (tryReleaseShared(arg)) {// 唤醒阻塞的线程doReleaseShared();return true;}// state不为0return 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;}}
