你好,游客 登录 注册 搜索
背景:
阅读新闻

多线程条件通行工具——CountDownLatch

[日期:2017-01-02] 来源:Linux社区  作者:hvicen [字体: ]

操作:

  • CountDownLatch(int)
    构造方法,指定初始计数。
  • await()
    等待计数减至0。
  • await(long, TimeUnit)
    在指定时间内,等待计数减至0。
  • countDown()
    计数减1。
  • getCount()
    获取剩余计数。

例子1:主线程创建了若干子线程,主线程需要等待这若干子线程结束后才结束。

例子2:线程有若干任务,分多个线程来完成,需要等待这若干任务被完成后,才继续运行处理。

源码:

/**
 * @since 1.5
 * @author Doug Lea
 */
public class CountDownLatch {

    private final Sync sync;

    public CountDownLatch(int count) {
        if (count < 0) throw new IllegalArgumentException("count < 0");
        this.sync = new Sync(count);
    }
    
    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) {
            // 当数量达到0时,才能通行,否则阻塞
            return (getState() == 0) ? 1 : -1;
        }

        protected boolean tryReleaseShared(int releases) {
            for (;;) {
                int c = getState();
                // 如果数量达到0,则释放失败
                if (c == 0)
                    return false;
                int nextc = c-1;
                // 尝试把数量递减
                if (compareAndSetState(c, nextc))
                    return nextc == 0;
            }
        }
    }

    public void await() throws InterruptedException {
        // 获取共享锁
        sync.acquireSharedInterruptibly(1);
    }

    public boolean await(long timeout, TimeUnit unit) throws InterruptedException {
        // 尝试获取共享锁
        return sync.tryAcquireSharedNanos(1, unit.toNanos(timeout));
    }

    public void countDown() {
        // 释放共享锁
        sync.releaseShared(1);
    }

    public long getCount() {
        return sync.getCount();
    }

    public String toString() {
        return super.toString() + "[Count = " + sync.getCount() + "]";
    }
}

本文永久更新链接地址http://www.linuxidc.com/Linux/2017-01/139061.htm

linux
相关资讯       CountDownLatch 
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款