操作:
- 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