閉鎖
閉鎖是一種同步工具類根时,可以延遲線程的進度直到線程到達終止狀態(tài)〕皆危可以用于確保某些活動直到其他活動都完成后繼續(xù)執(zhí)行:
- 確保某個計算在其需要的所有資源都被初始化之后繼續(xù)執(zhí)行
- 確保某個服務(wù)在其依賴的所有其他服務(wù)都已經(jīng)啟動之后才啟動蛤迎。
- 等待直到某個操作的所有參與者都就緒再繼續(xù)執(zhí)行。
閉鎖就像是一扇門含友,在閉鎖到達結(jié)束狀態(tài)之前替裆,這扇門一直關(guān)閉的校辩,并且沒有任何線程能夠通過,當?shù)竭_結(jié)束狀態(tài)時辆童,這扇門會打開并允許所有的線程通過宜咒。(當閉鎖到達結(jié)束狀態(tài)后,將不會再改變狀態(tài))
CountDownLatch 是一種靈活的閉鎖實現(xiàn)把鉴,可以使一個或多個線程等待一組事件發(fā)生故黑。閉鎖狀態(tài)包括一個計數(shù)器,該計數(shù)器被初始化成為一個正數(shù)庭砍,表示需要等待的事件數(shù)量场晶。countDown 方法遞減計數(shù)器,表示有一個事件已經(jīng)發(fā)生怠缸。await 方法等待計數(shù)器到達零诗轻,這表示所有需要等待的事件都已經(jīng)發(fā)生。
public class TestHarness {
public long timeTask(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++) {
new Thread(){
@Override
public void run() {
try {
startGate.await();
try {
task.run();
} finally {
endGate.countDown();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}.start();
}
long startTime = System.nanoTime();
startGate.countDown();
endGate.await();
long endTime = System.nanoTime();
return endTime - startTime;
}
public static void main(String[] args) throws InterruptedException {
long time = new TestHarness().timeTask(10, new Runnable() {
public void run() {
System.out.println("Current Thread : " + Thread.currentThread().getName());
}
});
System.out.println("Task execute time : " + time);
}
}
結(jié)果