CountDownLatch 用法
CountDownLatch 是一种闭锁,闭锁是一种同步工具类,可以延迟线程直到满足指定状态时再执行
CountDownLatch 常用于以下情形,当某个服务的启动要依赖于其他服务的完成情况
如serviceA需要serviceB, serviceC, serviceD的完成,使用countDownLatch可以轻松完成这种需求
public class TestHarness {
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;
}
}
代码摘自《java 并发编程实战》
在这里,每个线程在完成自己的工作时,会使endGate降1,同时用startGate来保证工作线程同时开启
网友评论