模拟公司所有员工都下班后,值班人员锁门离开公司。
import java.util.concurrent.CountDownLatch;
/** * @description: 模拟员工下班关门案例 * @author: xz */
public class CountDownLatchDemo1 {
public static void main(String[] args) throws InterruptedException {
closeDoor();
}
private static void closeDoor() throws InterruptedException {
//创建CountDownLatch,初始容量为10,模拟10名员工
CountDownLatch countDownLatch=new CountDownLatch(10);
for (int i=1;i<=10;i++){
new Thread(()->{
System.out.println(Thread.currentThread().getName() + "\t" + "忙完工作,下班。");
//计数器减1
countDownLatch.countDown();
},"员工编号:"+String.valueOf(i)).start();
}
//当计数器的值变为0,因调用await方法被阻塞的线程会被唤醒,继续执行
countDownLatch.await();
System.out.println(Thread.currentThread().getName() + "\t值班人员锁门离开公司");
}
}
模拟公司所有员工都下班后,值班人员锁门离开公司。
import lombok.Getter;
/** * @description: 枚举类,定义10名员工 * @author: xz * */
public enum EmpEnum {
ONE(1, "刘一"),
TWO(2, "陈二"),
THREE(3, "张三"),
FOUR(4, "李四"),
FIVE(5, "王五"),
SIX(6, "赵六"),
SEVEN(7, "孙七"),
EIGHT(8, "周八"),
NINE(9, "吴九"),
TEN(10, "郑十");
@Getter
private int code;//员工编号
@Getter
private String name;//员工名称
EmpEnum(Integer code, String name) {
this.code = code;
this.name = name;
}
public static EmpEnum forEach(int index) {
EmpEnum[] EmpEnums = EmpEnum.values();
for (EmpEnum epmEnum : EmpEnums) {
if (index == epmEnum.getCode()) {
return epmEnum;
}
}
return null;
}
}
public class CountDownLatchDemo2 {
public static void main(String[] args) throws InterruptedException {
closeDoor();
}
private static void closeDoor() throws InterruptedException {
//创建CountDownLatch,初始容量为10,模拟10名员工
CountDownLatch countDownLatch=new CountDownLatch(10);
for (int i=1;i<=10;i++){
new Thread(()->{
System.out.println(Thread.currentThread().getName() + "\t" + "忙完工作,下班。");
//计数器减1
countDownLatch.countDown();
},EmpEnum.forEach(i).getName()).start();
}
//当计数器的值变为0,因调用await方法被阻塞的线程会被唤醒,继续执行
countDownLatch.await();
System.out.println(Thread.currentThread().getName() + "\t值班人员锁门离开公司");
}
}
版权说明 : 本文为转载文章, 版权归原作者所有 版权申明
原文链接 : https://wwwxz.blog.csdn.net/article/details/122353217
内容来源于网络,如有侵权,请联系作者删除!