并发工具类闭锁CountDownLatch练习

[size=large]文章摘自【java并发编程实战】[/size]

1.[color=red]闭锁的作用相当于一扇门:在闭锁状态到达结束状态之前,这扇门一直是关闭着的,并且没有任何线程能够通过,当到达结束状态时,这扇门会打开并允许所有的线程通过。[/color]
2.[color=red]当闭锁到达结束状态,将不会再改变状态,因此这扇门将永远保持打开状态。[/color]


/**
* 统计所有线程执行完后所花费的时间
* @param nThreads 线程数
* @param task 任务
* @return 执行时间
* @throws InterruptedException
*/
public long timeTasks(int nThreads,final Runnable task) throws InterruptedException{
final CountDownLatch startGate = new CountDownLatch(1);
final CountDownLatch endGate = new CountDownLatch(nThreads);

for(int i=0;i<nThreads;i++){
Thread t = new Thread(){
public void run(){
try{
startGate.await();
try{
task.run();
}finally{
endGate.countDown();
}
}catch(InterruptedException ignored){}
}
};
t.start();
}

long start = System.nanoTime();
startGate.countDown();
endGate.await();
long end = System.nanoTime();
return end - start;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值