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