您现在的位置是:首页 > 文章详情

java源码 - CountDownLatch

日期:2018-09-01点击:342

开篇

  • CountDownLatch是一个同步工具类,用来协调多个线程之间的同步,或者说起到线程之间的通信(而不是用作互斥的作用)。

  • CountDownLatch能够使一个线程在等待另外一些线程完成各自工作之后,再继续执行。使用一个计数器进行实现。计数器初始值为线程的数量。当每一个线程完成自己任务后,计数器的值就会减一。当计数器的值为0时,表示所有的线程都已经完成了任务,然后在CountDownLatch上等待的线程就可以恢复执行任务。

  • CountDownLatch是一次性的,计数器的值只能在构造方法中初始化一次,之后没有任何机制再次对其设置值,当CountDownLatch使用完毕后,它不能再次被使用。


CountDownLatch的用法

  • CountDownLatch典型用法1:某一线程在开始运行前等待n个线程执行完毕。将CountDownLatch的计数器初始化为n new CountDownLatch(n) ,每当一个任务线程执行完毕,就将计数器减1 countdownlatch.countDown(),当计数器的值变为0时,在CountDownLatch上 await() 的线程就会被唤醒。一个典型应用场景就是启动一个服务时,主线程需要等待多个组件加载完毕,之后再继续执行。

  • CountDownLatch典型用法2:实现多个线程开始执行任务的最大并行性。注意是并行性,不是并发,强调的是多个线程在某一时刻同时开始执行。类似于赛跑,将多个线程放到起点,等待发令枪响,然后同时开跑。做法是初始化一个共享的CountDownLatch(1),将其计数器初始化为1,多个线程在开始执行任务前首先 coundownlatch.await(),当主线程调用 countDown() 时,计数器变为0,多个线程同时被唤醒。


CountDownLatch的demo

public class CountDownLatchDemo { public static void main(String[] args) throws InterruptedException{ CountDownLatch countDownLatch = new CountDownLatch(2){ @Override public void await() throws InterruptedException { super.await(); System.out.println(Thread.currentThread().getName() + " count down is ok"); } }; Thread thread1 = new Thread(new Runnable() { @Override public void run() { //do something try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName() + " is done"); countDownLatch.countDown(); } }, "thread1"); Thread thread2 = new Thread(new Runnable() { @Override public void run() { try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName() + " is done"); countDownLatch.countDown(); } }, "thread2"); thread1.start(); thread2.start(); countDownLatch.await(); } 


CountDownLatch的类定义

  • CountDownLatch内部包含Sync类。
  • CountDownLatch内部包含Sync类的对象sync。
  • Sync类继承自AQS(神奇的AQS),构造函数设置AQS的state值为等待值。
public class CountDownLatch { 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) { // Decrement count; signal when transition to zero for (;;) { int c = getState(); if (c == 0) return false; int nextc = c-1; if (compareAndSetState(c, nextc)) return nextc == 0; } } } private final Sync sync; public CountDownLatch(int count) { if (count < 0) throw new IllegalArgumentException("count < 0"); this.sync = new Sync(count); } } 


CountDownLatch的等待过程

  • CountDownLatch通过await()进入等待。
  • CountDownLatch通过await(long timeout, TimeUnit unit)进入超时等待。
 public void await() throws InterruptedException { sync.acquireSharedInterruptibly(1); } public boolean await(long timeout, TimeUnit unit) throws InterruptedException { return sync.tryAcquireSharedNanos(1, unit.toNanos(timeout)); } 



CountDownLatch的await()过程

  • await()通过sync.acquireSharedInterruptibly()获锁。
  • acquireSharedInterruptibly通过tryAcquireShared()尝试获锁。
  • tryAcquireShared()判断获锁成功与否的依据是AQS的state的值是否为零。
  • 获锁失败后通过doAcquireSharedInterruptibly()进入锁等待队列CLH。
 public void await() throws InterruptedException { sync.acquireSharedInterruptibly(1); } public final void acquireSharedInterruptibly(int arg) throws InterruptedException { if (Thread.interrupted()) throw new InterruptedException(); // 尝试获锁失败 if (tryAcquireShared(arg) < 0) // doAcquireSharedInterruptibly(arg); } protected int tryAcquireShared(int acquires) { return (getState() == 0) ? 1 : -1; } private void doAcquireSharedInterruptibly(int arg) throws InterruptedException { final Node node = addWaiter(Node.SHARED); boolean failed = true; try { for (;;) { final Node p = node.predecessor(); if (p == head) { int r = tryAcquireShared(arg); if (r >= 0) { setHeadAndPropagate(node, r); p.next = null; // help GC failed = false; return; } } if (shouldParkAfterFailedAcquire(p, node) && parkAndCheckInterrupt()) throw new InterruptedException(); } } finally { if (failed) cancelAcquire(node); } } 



CountDownLatch的await(long timeout, TimeUnit unit)过程

  • await(long timeout, TimeUnit unit)通过sync.tryAcquireSharedNanos()获锁。
  • tryAcquireSharedNanos()通过doAcquireSharedNanos()尝试获锁。
  • tryAcquireShared()判断获锁成功与否的依据是AQS的state的值是否为零。
  • 获锁失败后通过doAcquireSharedNanos()进入锁等待队列CLH,和doAcquireSharedInterruptibly()方法相比增加了超时检测机制,通过LockSupport.parkNanos()实现超时。
 public boolean await(long timeout, TimeUnit unit) throws InterruptedException { return sync.tryAcquireSharedNanos(1, unit.toNanos(timeout)); } public final boolean tryAcquireSharedNanos(int arg, long nanosTimeout) throws InterruptedException { if (Thread.interrupted()) throw new InterruptedException(); return tryAcquireShared(arg) >= 0 || doAcquireSharedNanos(arg, nanosTimeout); } private boolean doAcquireSharedNanos(int arg, long nanosTimeout) throws InterruptedException { if (nanosTimeout <= 0L) return false; final long deadline = System.nanoTime() + nanosTimeout; final Node node = addWaiter(Node.SHARED); boolean failed = true; try { for (;;) { final Node p = node.predecessor(); if (p == head) { int r = tryAcquireShared(arg); if (r >= 0) { setHeadAndPropagate(node, r); p.next = null; // help GC failed = false; return true; } } nanosTimeout = deadline - System.nanoTime(); if (nanosTimeout <= 0L) return false; if (shouldParkAfterFailedAcquire(p, node) && nanosTimeout > spinForTimeoutThreshold) LockSupport.parkNanos(this, nanosTimeout); if (Thread.interrupted()) throw new InterruptedException(); } } finally { if (failed) cancelAcquire(node); } } 


CountDownLatch的唤醒过程

  • CountDownLatch通过sync.releaseShared(1)释放锁实现state的递减
  • tryReleaseShared()方法判断锁状态state==0,递减后值为0说明锁已经被释放。
  • releaseShared()释放锁成功后通过doReleaseShared()方法唤醒所有等待线程。
  • doReleaseShared()唤醒锁的过程是一个传播性的唤醒,通过线程A唤醒线程B,然后由线程B唤醒线程C的传播性依次唤醒所有等待线程。
 public void countDown() { sync.releaseShared(1); } public final boolean releaseShared(int arg) { if (tryReleaseShared(arg)) { doReleaseShared(); return true; } 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; } } private void doReleaseShared() { for (;;) { Node h = head; if (h != null && h != tail) { int ws = h.waitStatus; if (ws == Node.SIGNAL) { if (!compareAndSetWaitStatus(h, Node.SIGNAL, 0)) continue; // loop to recheck cases unparkSuccessor(h); } else if (ws == 0 && !compareAndSetWaitStatus(h, 0, Node.PROPAGATE)) continue; // loop on failed CAS } if (h == head) // loop if head changed break; } } 


总结

CountDownLatch的工作原理,总结起来就两点(基于AQS实现):

  • 初始化锁状态的值为需要等待的线程数。
  • 判断锁状态是否已经释放,如果锁未释放所有等待锁的线程就会进入等待的CLH队列。
  • 如果锁状态已经释放,那么就会通过传播性唤醒所有的等待线程。
原文链接:https://yq.aliyun.com/articles/666307
关注公众号

低调大师中文资讯倾力打造互联网数据资讯、行业资源、电子商务、移动互联网、网络营销平台。

持续更新报道IT业界、互联网、市场资讯、驱动更新,是最及时权威的产业资讯及硬件资讯报道平台。

转载内容版权归作者及来源网站所有,本站原创内容转载请注明来源。

文章评论

共有0条评论来说两句吧...

文章二维码

扫描即可查看该文章

点击排行

推荐阅读

最新文章