一.使用

1个线程等待多个线程执行完成后再执行。

  1. public class CountDownLatch1 {
  2. public static void main(String[] args) throws InterruptedException {
  3. CountDownLatch countDownLatch = new CountDownLatch(5);
  4. for (int i = 0; i < 5; i++) {
  5. new Thread(new Runnable() {
  6. @SneakyThrows
  7. @Override
  8. public void run() {
  9. Thread.sleep(3000);
  10. System.out.println("countDown");
  11. countDownLatch.countDown();
  12. }
  13. }).start();
  14. }
  15. System.out.println("await");
  16. countDownLatch.await();
  17. System.out.println("---------------");
  18. }
  19. }
  20. 输出:
  21. await
  22. countDown
  23. countDown
  24. countDown
  25. countDown
  26. countDown
  27. ---------------

多个线程等待1个线程执行完成后再执行。

  1. public class CountDownLatch2 {
  2. public static void main(String[] args) throws InterruptedException {
  3. CountDownLatch countDownLatch = new CountDownLatch(1);
  4. for (int i = 0; i < 5; i++) {
  5. new Thread(new Runnable() {
  6. @SneakyThrows
  7. @Override
  8. public void run() {
  9. System.out.println("await");
  10. countDownLatch.await();
  11. System.out.println("hello");
  12. }
  13. }).start();
  14. }
  15. Thread.sleep(3000);
  16. System.out.println("countDown");
  17. countDownLatch.countDown();
  18. }
  19. }
  20. 输出:
  21. await
  22. await
  23. await
  24. await
  25. await
  26. countDown
  27. hello
  28. hello
  29. hello
  30. hello
  31. hello

二.源码

1.构造函数

  1. public CountDownLatch(int count) {
  2. this.sync = new Sync(count);
  3. }
  4. private static final class Sync extends AbstractQueuedSynchronizer {
  5. Sync(int count) {
  6. setState(count);
  7. }
  8. }

2.await

  1. public void await() throws InterruptedException {
  2. sync.acquireSharedInterruptibly(1);
  3. }
  4. public final void acquireSharedInterruptibly(int arg)
  5. throws InterruptedException {
  6. // 初始时state不是0
  7. if (tryAcquireShared(arg) < 0)
  8. // 没拿到锁,入队阻塞
  9. doAcquireSharedInterruptibly(arg);
  10. }
  11. protected int tryAcquireShared(int acquires) {
  12. return (getState() == 0) ? 1 : -1;
  13. }

3.countDown

  1. public void countDown() {
  2. sync.releaseShared(1);
  3. }
  4. public final boolean releaseShared(int arg) {
  5. // state为0
  6. if (tryReleaseShared(arg)) {
  7. // 唤醒阻塞的线程
  8. doReleaseShared();
  9. return true;
  10. }
  11. // state不为0
  12. return false;
  13. }
  14. protected boolean tryReleaseShared(int releases) {
  15. for (;;) {
  16. int c = getState();
  17. if (c == 0)
  18. return false;
  19. int nextc = c-1;
  20. if (compareAndSetState(c, nextc))
  21. // 执行到这
  22. return nextc == 0;
  23. }
  24. }