CountDownLatch

CountDownLatch是一个计数器 ,可以线程安全的进行latch.countDown();当count减为0时,latch.await();方法停止阻塞。线程完成一个记录一个,计数器递减,只能只用一次

demo

  1. ublic class Parallellimit {
  2. public static void main(String[] args) {
  3. ExecutorService pool = Executors.newCachedThreadPool();
  4. CountDownLatch cdl = new CountDownLatch(100);
  5. for (int i = 0; i < 100; i++) {
  6. CountRunnable runnable = new CountRunnable(cdl);
  7. pool.execute(runnable);
  8. }
  9. }
  10. }
  11. class CountRunnable implements Runnable {
  12. private CountDownLatch countDownLatch;
  13. public CountRunnable(CountDownLatch countDownLatch) {
  14. this.countDownLatch = countDownLatch;
  15. }
  16. @Override
  17. public void run() {
  18. try {
  19. synchronized (countDownLatch) {
  20. countDownLatch.countDown();
  21. System.out.println("thread counts = " + (countDownLatch.getCount()));
  22. }
  23. countDownLatch.await();
  24. System.out.println("concurrency counts = " + (100 - countDownLatch.getCount()));
  25. } catch (InterruptedException e) {
  26. e.printStackTrace();
  27. }
  28. }
  29. }

源码

CountDownLatch使用内部类Sync继承aqs来保证线程安全

 private static final class Sync extends AbstractQueuedSynchronizer {
        private static final long serialVersionUID = 4982264981922014374L;

        Sync(int count) {
            this.setState(count);
        }

        int getCount() {
            return this.getState();
        }

        protected int tryAcquireShared(int acquires) {
            return this.getState() == 0 ? 1 : -1;
        }

        protected boolean tryReleaseShared(int releases) {
            int c;
            int nextc;
            do {
                c = this.getState();
                if (c == 0) {
                    return false;
                }

                nextc = c - 1;
            } while(!this.compareAndSetState(c, nextc));

            return nextc == 0;
        }
    }