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

CountDownLatch的作用是,线程进入等待后,需要计数器达到0才能通行。

  • 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() + "]";
    }
}
原文地址:https://www.cnblogs.com/hvicen/p/6241976.html