[size=large]文章摘自【java并发编程实战】[/size]
1.[color=red]闭锁的作用相当于一扇门:在闭锁状态到达结束状态之前,这扇门一直是关闭着的,并且没有任何线程能够通过,当到达结束状态时,这扇门会打开并允许所有的线程通过。[/color]
2.[color=red]当闭锁到达结束状态,将不会再改变状态,因此这扇门将永远保持打开状态。[/color]
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;
}
本文介绍了如何利用闭锁(CountDownLatch)来同步多个线程的执行,确保所有线程完成指定任务后再继续后续操作。闭锁如同一扇门,在到达结束状态前阻止线程通过,一旦状态变为结束则永久开放。
1731

被折叠的 条评论
为什么被折叠?



