Java系列之CountDownLatch

版权声明: https://blog.csdn.net/ph3636/article/details/84946117

1. CountDownLatch代表多个操作都执行完时整个程序才可以继续向下执行。数量可以设置

public CountDownLatch(int count) {
        if (count < 0) throw new IllegalArgumentException("count < 0");
        this.sync = new Sync(count);
    }

2. 主程序等待其他多个操作执行完毕才可以继续执行,可以设置等待时间

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 final void acquireSharedInterruptibly(int arg)
            throws InterruptedException {
        if (Thread.interrupted())
            throw new InterruptedException();
        if (tryAcquireShared(arg) < 0)
            doAcquireSharedInterruptibly(arg);
    }

public final boolean tryAcquireSharedNanos(int arg, long nanosTimeout)
            throws InterruptedException {
        if (Thread.interrupted())
            throw new InterruptedException();
        return tryAcquireShared(arg) >= 0 ||
            doAcquireSharedNanos(arg, nanosTimeout);
    }

尝试获取允许,这里会判断允许量是否为0,也就是所有的其他操作都释放了允许量即执行了countDown操作

protected int tryAcquireShared(int acquires) {
            return (getState() == 0) ? 1 : -1;
        }

3. 释放许可量countDown

public void countDown() {
        sync.releaseShared(1);
    }

 public final boolean releaseShared(int arg) {
        if (tryReleaseShared(arg)) {
            doReleaseShared();
            return true;
        }
        return false;
    }

尝试释放许可量,这里是对初始量进行减一操作,也就是当许可量为0时才会返回true。

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. 这个类只能使用一次,因为这个许可量只会减少而不会增加,所以如果想多次使用的话,可以增加一个方法把许可量设置成以前设置过的值,即在CountDownLatch初始化时保存上初始设置值

 private final int startCount;

        Sync(int count) {
            this.startCount = count;
            setState(count);
        }

最后通过复位操作就可以达到重复使用

 protected void reset() {
            setState(startCount);
        }

猜你喜欢

转载自blog.csdn.net/ph3636/article/details/84946117