package com.huang.test.concurrent;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
/**
* 倒计时测试,多个线程调用countdown,当countdown为0的时候执行后续操作(不可重复使用)
*/
public class CountdownlatchTest {
class MyThread extends Thread
{
private int sec;
private CountDownLatch cdt;
public MyThread(int sec, CountDownLatch cdt)
{
this.sec = sec;
this.cdt = cdt;
}
@Override
public void run() {
super.run();
System.out.println("thread " + sec + " start...");
try {
Thread.sleep(sec * 1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("thread " + sec + " end...");
cdt.countDown();
}
}
private void test() {
CountDownLatch cdt = new CountDownLatch(5);
int len = 5;
for(int i = 0; i < len;i++)
{
new MyThread(i, cdt).start();
}
try {
boolean res = cdt.await(6, TimeUnit.SECONDS);
System.out.println("await: " + res);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("all end....");
}
public static void main(String[] args) {
CountdownlatchTest ct = new CountdownlatchTest();
ct.test();
}
}