一種同步工具類,可以延遲線程的進(jìn)度直到閉鎖的值等于0(終止?fàn)顟B(tài))
可用于在執(zhí)行一個(gè)任務(wù)前,必須把這個(gè)任務(wù)前的全部完成,才能執(zhí)行這個(gè)任務(wù)。
比如,游戲要等所有玩家都準(zhǔn)備好之后才開始 所有資源都初始化之后才開始加載類。
t.start();啟動(dòng)線程后繼續(xù)向下執(zhí)行,不過線程會(huì)在startGate.await();的地方等待
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 {
//所有線程啟動(dòng)后,都會(huì)在這個(gè)地方等待startGate閉鎖等于0
startGate.await();
try {
//雖然是實(shí)現(xiàn)了runnable 不過task.run()不會(huì)啟動(dòng)線程 和執(zhí)行普通方法一樣
task.run();
} finally {
//每一個(gè)線程執(zhí)行任務(wù)之后,countdown
endGate.countDown();
}
} catch (InterruptedException ignored) {
}
}
};
t.start();
}
long start = System.nanoTime();
//打開閉鎖 startGate
startGate.countDown();
//等待endGate閉鎖等0之后,繼續(xù)向下執(zhí)行
endGate.await();
long end = System.nanoTime();
return end - start;
}