import java.util.concurrent.CountDownLatch;
/**
* 多线程完成之后,主线程才可以继续;倒计时
* 例子:秦灭六国 统一
*/
public class CountDownLatchDemo {
//秦灭六国 统一
private static final int num = CountryEnum.values().length;
CountDownLatch countDownLatch= new CountDownLatch(num);
for (int i = 0; i < num; i++) {
final int tem = i;
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
System.out.println(Thread.currentThread().getName() +"灭亡");
countDownLatch.countDown();
}
});
thread.setName(CountryEnum.foreach_CountryEnum(i).getValue());
thread.start();
}
countDownLatch.await();
System.out.println("秦朝统一");
}
enum CountryEnum {
ONE(1,"齐"),TWO(2,"楚"),THREE(3,"燕"),FOUR(4,"韩"),FIVE(5,"赵"),SIX(6,"魏");
private int code;
private String value;
CountryEnum(int code,String value){
this.code = code;
this.value = value;
}
//枚举类遍历
public static CountryEnum foreach_CountryEnum(int code){
CountryEnum[] myArray = CountryEnum.values();
for (CountryEnum countryEnum : myArray){
if(code == countryEnum.getCode()){
return countryEnum;
}
}
return null;
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}