CountDownLatch,一个同步辅助类,在完成一组正在其他线程中执行的操作之前,它允许一个或多个线程一直等待,直到其他操作完成或超时。
源码分析
CountDownLatch的实现方式是在内部定义了一个实现AbstractQueuedSynchronizer(详见:JUC - AbstractQueuedSynchronizer(AQS) 源码分析)的内部类Sync,Sync主要实现了AbstractQueuedSynchronizer中共享模式的获取和释放方法tryAcquireShared和tryReleaseShared,在CountDownLatch中使用AQS的子类Sync,初始化的state表示一个计数器,每次countDown的时候计数器会减少1,直到减为0的时候或超时或中断,await方法从等待中返回。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| private static final class Sync extends AbstractQueuedSynchronizer { private static final long serialVersionUID = 4982264981922014374L; 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; } } }
|
1 2 3
| public void await() throws InterruptedException { sync.acquireSharedInterruptibly(1); }
|
1 2 3
| public void countDown() { sync.releaseShared(1); }
|
使用方式
常见使用场景示例:主线程等待子线程都执行完任务后才返回。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
| public class CountDownLatchTest { public static void main(String[] args) throws InterruptedException { final CountDownLatch c = new CountDownLatch(3); Thread thread = new Thread(new Runnable() { @Override public void run() { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } c.countDown(); System.out.println("countDown 1000 : " + c.getCount()); } }); thread.start(); Thread thread2 = new Thread(new Runnable() { @Override public void run() { try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } c.countDown(); System.out.println("countDown 2000 : " + c.getCount()); } }); thread2.start(); Thread thread3 = new Thread(new Runnable() { @Override public void run() { try { Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } c.countDown(); System.out.println("countDown 3000 : " + c.getCount()); } }); thread3.start(); System.out.println("await before : " + c.getCount()); c.await(); System.out.println("await after : " + c.getCount()); } }
|