倒計時器,某個線程可以等待這個倒計時指向0的時候開始執行:
final CountDownLatch cdl = new CountDownLatch(10);
for(int i = 0;i<10;i++){
final int index = i;
new Thread(new Runnable(){
@Override
public void run() {
try {
Thread.sleep(new Random().nextInt(5000));
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("thread " + index + " execute complate!");
cdl.countDown();
}
}).start();
}
System.out.println("main thread is awaiting...");
try {
cdl.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("all thread execute complate.");
主線程啓動10個線程開始來減少倒計時數量,等到減到0時主線程繼續執行,結果如下:
main thread is awaiting...
thread 0 execute complate!
thread 8 execute complate!
thread 2 execute complate!
thread 4 execute complate!
thread 9 execute complate!
thread 7 execute complate!
thread 5 execute complate!
thread 1 execute complate!
thread 6 execute complate!
thread 3 execute complate!
all thread execute complate.