注: 本帖源于尚硅谷阳哥
一. 灭七国
import lombok.Getter;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
public class CountDownLatchDemo {
public static void main(String[] args) {
CountDownLatch countDownLatch = new CountDownLatch(6);
for (int i = 0; i < 6; i++) {
int finalI = i;
new Thread(
() -> {
System.out.println(
Thread.currentThread().getName()
+ ": "
+ CountryEnum.getNameByCode(finalI)
+ "被灭");
try {
//计数, 达到域值唤醒另一线程
countDownLatch.countDown();
} catch (Exception e) {
e.printStackTrace();
} finally {
}
},
"t" + i)
.start();
}
new Thread(
() -> {
try {
// 等待唤醒
countDownLatch.await(1500, TimeUnit.MILLISECONDS);
System.out.println("秦,一统六国");
} catch (InterruptedException e) {
e.printStackTrace();
}
},
"")
.start();
}
enum CountryEnum {
ONE(1, "楚国"),
TWO(2, "齐国"),
THR(3, "燕国"),
FOU(4, "韩国"),
FIV(5, "赵国"),
SIX(6, "魏国");
@Getter private Integer retCode;
@Getter private String retName;
CountryEnum(Integer retCode, String retName) {
this.retCode = retCode;
this.retName = retName;
}
public static String getNameByCode(Integer i) {
for (CountryEnum element : CountryEnum.values()) {
if (element.getRetCode().equals(Integer.valueOf(i))) {
return element.getRetName();
}
}
return null;
}
}
}
二.
三.
四.
等等
..............有时间再补充吧....................