閉鎖可以延遲線程的進度直到其到達終止狀態;
/**
* nThreads線程同時完成task,計算消耗時間
* startGate保證在所有線程都創建好後,同時釋放所有工作線程;
* endGate保證 主線程 等待 最後一個工作線程執行完成。
**/
public static 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{
System.out.println(Thread.currentThread().getName()+"func");
startGate.await();//所有工作線程在此等待startGate的開啓
try{
task.run();//工作線程開啓後 run
}finally{
endGate.countDown();
}
}catch(InterruptedException ignored){}
}
};
t.start();
}
long start =System.nanoTime();
System.out.println(Thread.currentThread().getName());
startGate.countDown();//釋放所有工作線程
endGate.await();//主線程等待最後一個線程執行完畢
long end =System.nanoTime();
return end-start;
}
public static void main(String[] args) {
try {
System.out.println(timeTasks(3,new Runnable(){
@Override
public void run() {
// TODO Auto-generated method stub
System.out.println(Thread.currentThread().getName()+"main");
}
}));
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
輸出:
Thread-0func
Thread-1func
Thread-2func
main
Thread-0main
Thread-2main
Thread-1main
20965901698
簡易版,主線程等待五個任務線程執行完畢,再執行
public class CountDownLatchTest {
public static void main(String[] args) {
final CountDownLatch countDownLatch = new CountDownLatch(5);
for(int i = 0; i < 5; i ++) {
new Thread(new Runnable() {
//@Override
public void run(){
System.out.println(Thread.currentThread().getName() +" run");
try {
Thread.sleep(5000l);
} catch (InterruptedException e) {
e.printStackTrace();
}
countDownLatch.countDown();
}
}).start();
}
try {
countDownLatch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("all thread over");
}
}
輸出:
Thread-1 run
Thread-4 run
Thread-2 run
Thread-0 run
Thread-3 run
all thread over