读CountDownLatch源码_JAVA_编程开发_程序员俱乐部

中国优秀的程序员网站程序员频道CXYCLUB技术地图
热搜:
更多>>
 
您所在的位置: 程序员俱乐部 > 编程开发 > JAVA > 读CountDownLatch源码

读CountDownLatch源码

 2017/9/1 16:08:52  红领巾丶  程序员俱乐部  我要评论(0)
  • 摘要://在完成一组操作之前允许一个或多个线程等待内部用的AQSprivatestaticfinalclassSyncextendsAbstractQueuedSynchronizer{privatestaticfinallongserialVersionUID=4982264981922014374L;Sync(intcount){setState(count);}intgetCount(){returngetState();}protectedinttryAcquireShared
  • 标签:源码
class="java">
//在完成一组操作之前允许一个或多个线程等待内部用的AQS

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;
            }
        }
    }


//先看构造函数
public CountDownLatch(int count) {
        if (count < 0) throw new IllegalArgumentException("count < 0");
	//初始化sync.
        this.sync = new Sync(count);
    }


//阻塞当前线程
public void await() throws InterruptedException {
        sync.acquireSharedInterruptibly(1);
    }

//阻塞指定时间超时返回false
public boolean await(long timeout, TimeUnit unit)
        throws InterruptedException {
        return sync.tryAcquireSharedNanos(1, unit.toNanos(timeout));
    }

//递减count.0则唤醒等待的所有线程。
public void countDown() {
        sync.releaseShared(1);
    }

//获取当前计数器数量
public long getCount() {
        return sync.getCount();
    }

public String toString() {
        return super.toString() + "[Count = " + sync.getCount() + "]";
    }
发表评论
用户名: 匿名