CountDownLatch源代码分析
1.首先分析它的功能:A synchronization aid that allows one or more threads to wait until a set of operations being performed in other threads completes.
也就是说主线程在等待所有其它的子线程完成后再往下执行。常见的例子是待所有的运动员跑完后再排名。
2.它所提供的方法如下:
构造函数:CountDownLatch(int count)//初始化count数目的同步计数器,只有当同步计数器为0,主线程才会向下执行
主要方法:voidawait()//当前线程等待计数器为0
booleanawait(long timeout, TimeUnit unit)//与上面的方法不同,它加了一个时间限制。
voidcountDown()//计数器减1
longgetCount()//获取计数器的值
3.它的内部有一个辅助的内部类:sync.
它的实现如下:private static final class Sync extends AbstractQueuedSynchronizer {
private static final long serialVersionUID = 4982264981922014374L;
/*此处在new CountDownLatch时会调用:
public CountDownLatch(int count) {
if (count < 0) throw new IllegalArgumentException("count < 0");
this.sync = new Sync(count);
}*/
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;
}
}
}
4.await()方法的实现
sync.acquireSharedInterruptibly(1);
-->if (tryAcquireShared(arg) < 0)//调用3中的tryAcquireShared()方法
doAcquireSharedInterruptibly(arg);//加入到等待队列中
5.countDown()方法的实现
sync.releaseShared(1);
--> if (tryReleaseShared(arg))//调用3中的tryReleaseShared()方法
doReleaseShared();//解锁
来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/30024515/viewspace-1432825/,如需转载,请注明出处,否则将追究法律责任。