[多线程]闭锁 通过闭锁CountDownLatch计算多线程下任务的执行时间

时间:2021-07-19 08:25:12

闭锁是一种同步工具类,可以延迟线程的进度直到其达到终止状态。

程序中有两个CountDownLatch, startGate为启动门,用于控制所有的线程都启动后才开始同时执行。 endGate为终止门,用于控制所有的线程都执行结束才终止计时。

/**
* 闭锁
* @param nThreads, 线程数
* @param task
* @return
*/
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() {

@Override
public void run() {
try {
startGate.await();
try {
task.run();
} finally {
endGate.countDown();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
t.start();
}

long startTime = System.currentTimeMillis();
startGate.countDown();
endGate.await();
long endTime = System.currentTimeMillis();
return endTime - startTime;
}