浅谈CountDownLatch这个对象的使用及原理

浅谈CountDownLatch这个对象的使用及原理

本文章仅作为本人学习记录,防止遗忘。

首先说一下,最近为什么想说一下这个对象?
最近公司在开发一个交易系统,由于客户需求的变动需要通过不同维度(产品、商户等等)将交易数据进行统计,单个串行执行接口耗时太长,加上各维度统计是相互隔离的,最后想到了用CountDownLatch这个对象。

  1. CountDownLatch 是什么?
    CountDownLatch 可以使一个或多个线程等待其他线程执行完毕后再执行!

  2. 为什么用 CountDownLatch?
    由于在工作中,我们进行统计时会遇到多个不互相关联的统计维度统计,但一个一个维度的统计执行太耗费时间了,导致后端提供的接口响应时间延长,这样就对前端太不友好了。所以我们需要优化接口的查询速度,那么多线程统计就是一个不错的选择。但是各个线程的执行时间不一样,我们无法保证各线程统一执行完,再由接口返回给前端。
    要想解决这个问题我们可以用CountDownLatch 实现。

  3. CountDownLatch 常用的三个方法
    CountDownLatch(int count):构造方法,创建一个值为count 的计数器。

    await() / await(long timeout, TimeUnit unit):阻塞当前线程,将当前线程加入阻塞队列。timeout: 表示timeout的时间之内阻塞当前线程,时间一过则当前线程可以执行。

    countDown():对计数器进行递减1操作,当计数器递减至0时,当前线程会去唤醒阻塞队列里的所有线程。

  4. 怎么使用CountDownLatch ?
    ① 创建计数器:CountDownLatch countDownLatch = new CountDownLatch(N); (N 代表要统计几个维度或者叫指标)
    ② 在每个线程执行完后调用countDown() 标记线程任务执行完毕。
    ③ 调用await() 方法让主线程等待所有线程执行完毕后在执行。

  5. CountDownLatch 常用方法代码原理JDK环境1.8]:
    CountDownLatch(int count)方法:

 /**
     * Constructs a {@code CountDownLatch} initialized with the given count.
     *
     * @param count the number of times {@link #countDown} must be invoked
     *        before threads can pass through {@link #await}
     * @throws IllegalArgumentException if {@code count} is negative
     */
    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) {
            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;
            }
        }
    }

await() 方法:

public void await() throws InterruptedException {
        sync.acquireSharedInterruptibly(1);
    }
 // 下边两个方法是AbstractQueuedSynchronizer 的方法
 public final void acquireSharedInterruptibly(int arg) throws InterruptedException {
        if (Thread.interrupted())
            throw new InterruptedException();
        if (tryAcquireShared(arg) < 0)
            doAcquireSharedInterruptibly(arg);
    }
  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);
        }
 }

countDown()方法:

public void countDown() {
        sync.releaseShared(1); //递减锁重入次数,当state=0时唤醒所有阻塞线程
}
public final boolean releaseShared(int arg) {
        if (tryReleaseShared(arg)) {
            doReleaseShared();
            return true;
        }
        return false;
}
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;
        }
    }

若有不足,望指正!
参考网址:https://www.jianshu.com/p/3c6315b4923b

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值