1、闭锁是一种synchronizer,它可以延迟线程的进度直到线程到达终止状态。
2、CountDownLatch是一个灵活的闭锁实现:
1) 允许一个或多个线程等待一个事件集的发生,闭锁的状态包括一个计数器,初始化为一个正数,用来实现需要等待的事件数。
2)countDown对计数器做减操作,表示一个事件已经发生了,而await方法等待计数器达到0,此时所有需要等待的事件都已经发生。
3)如果计数器的入口时值为非零,await会一直阻塞直到计数器为0,或等待线程中断及超时。
3、
使用CountDownLatch启动和停止线程
pulbic class TestHarness{
public long timeTasks(intnThreads,final Runnable task) throws InterruptedException{
finalCountDownLatch startGate=new CountDownLatch(1);
final CountDownLatch endGate=new CountDOwnLatch(nThreads);
for (int i=0;i<nThreads;i++){
THread t=new Thread(){
publicvoid 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,它允许一个或多个线程等待一系列事件的发生。文章详细展示了如何通过CountDownLatch来启动和停止线程,并解释了其核心组件如计数器的作用。
368

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



