CountDownLatch源码解析
countDownLatch是一个用来实现同步的工具,允许一个或者多个线程等待其他的线程完成一系列的操作。
类定义
public class CountDownLatch{}
属性定义
private final Sync sync;
Sync是一个内部类,一个同步器。
内部类Sync的定义
private static final class Sync extends AbstractQueuedSynchronizer{
private static final long serialVersionUID = 4982264981922014374L;
Sync(int count){
setState(count);
}
int getCount(){
getState();
}
protected int tryAcquireShared(int acquires){
return (getState() == 0) ? 1 : -1;
}
protected boolean tryReleaseShared(int releases){
// 减少count的值,当count的值变成0时,返回
for(;;){
int c = getState();
if(c == 0)
return false;
int nextc = c - 1;
if(compareAndSetState(c, nextc))
return nextc == 0;
}
}
}
Sync是AbstractQueuedSynchronizer的子类。CountDownLatch的同步控制器,使用AQS的state来代表count。
构造函数
public CountDownLatch(int count){
if(count < 0) throw new IllegalArgumentException("count < 0");
this.sync = new Sync(count);
}
使用给定的count创建一个CountDownLatch对象。
方法
// 会导致当前线程进入等待状态,直到count的值变成0,或者被中断
public void await() throws InterruptedException{
sync.acquireSharedInterruptibly(1);
}
// 与await相同,只不过增加了超时的功能
public boolean await(long timeout, TimeUnit unit) throws InterruptedException{
return sync.tryAcquireSharedNanos(1, unit.toNanos(timeout));
}
// 使count的值减一,如果count的值变成0,会唤醒所有等待的线程.
public void countDown(){
sync.releaseShared(1);
}
// 获取count的值
public long getCount(){
return sync.getCount();
}
public String toString(){
return super.toString() + "[Count = " + sync.getCount() + "]";
}