ITPub博客

首页 > 应用开发 > Java > CountDownLatch源代码分析

CountDownLatch源代码分析

原创 Java 作者:我思我存在 时间:2015-02-10 22:17:53 0 删除 编辑
CountDownLatch源代码分析
1.首先分析它的功能:A synchronization aid that allows one or more threads to wait until a set of operations being performed in other threads completes.
也就是说主线程在等待所有其它的子线程完成后再往下执行。常见的例子是待所有的运动员跑完后再排名。


2.它所提供的方法如下:
构造函数:CountDownLatch(int count)//初始化count数目的同步计数器,只有当同步计数器为0,主线程才会向下执行
主要方法:void await()//当前线程等待计数器为0 
      boolean await(long timeout, TimeUnit unit)//与上面的方法不同,它加了一个时间限制。
      void countDown()//计数器减1
      long getCount()//获取计数器的值


3.它的内部有一个辅助的内部类:sync.
它的实现如下:private static final class Sync extends AbstractQueuedSynchronizer {
        private static final long serialVersionUID = 4982264981922014374L;
        /*此处在new CountDownLatch时会调用: 
 public CountDownLatch(int count) {
              if (count < 0) throw new IllegalArgumentException("count < 0");
              this.sync = new Sync(count);
        }*/
        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;
            }
        }
    }

4.await()方法的实现
  sync.acquireSharedInterruptibly(1);
     -->if (tryAcquireShared(arg) < 0)//调用3中的tryAcquireShared()方法
            doAcquireSharedInterruptibly(arg);//加入到等待队列中

5.countDown()方法的实现
  sync.releaseShared(1);
     --> if (tryReleaseShared(arg))//调用3中的tryReleaseShared()方法
               doReleaseShared();//解锁

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/30024515/viewspace-1432825/ ,如需转载,请注明出处,否则将追究法律责任。

下一篇: 慢谈JAVA锁机制
请登录后发表评论 登录
全部评论

注册时间:2014-11-16

  • 博文量
    15
  • 访问量
    45296