java类contdownlatch源码,CountDownLatch源代码分析

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

--&gtif (tryAcquireShared(arg) < 0)//调用3中的tryAcquireShared()方法

doAcquireSharedInterruptibly(arg);//加入到等待队列中

5.countDown()方法的实现

sync.releaseShared(1);

--&gt if (tryReleaseShared(arg))//调用3中的tryReleaseShared()方法

doReleaseShared();//解锁

来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/30024515/viewspace-1432825/,如需转载,请注明出处,否则将追究法律责任。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值