CountDownLatch实现线程让领导先行

本文通过一个火灾逃生场景的代码示例,演示了如何使用Java并发工具包中的CountDownLatch来协调多线程操作,确保所有军官先行撤离后再允许普通民众离开,展示了CountDownLatch在控制线程同步中的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

CountDownLatch latch = new CountDownLatch(OFFICER_SIZE);//初始化计数器
latch.countDown();//计数器减一
latch.await();// 等待计数器为零
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class LatchDemo {
    public static final int OFFICER_SIZE = 80;// 0000000;

    public static final int COMMON_PEOPLE_SIZE = 20;

    public static void main(String[] args) {
        ExecutorService exeuctor = Executors.newCachedThreadPool();
        // must share the single latch
        CountDownLatch latch = new CountDownLatch(OFFICER_SIZE);
        System.out.println("the building is fire!");

        for (int i = 0; i < COMMON_PEOPLE_SIZE; i++) {
            exeuctor.execute(new commonPeople(i, latch));
        }

        for (int i = 0; i < OFFICER_SIZE; i++) {
            exeuctor.execute(new officer(i, latch));
        }
        exeuctor.shutdown();
    }

    static class officer implements Runnable {
        private int id;

        private CountDownLatch latch;

        public officer(int id, CountDownLatch latch) {
            this.id = id;
            this.latch = latch;
        }

        @Override
        public void run() {
            goOut();
            latch.countDown();
        }

        private void goOut() {
            System.out.println("I must go firstly when fire! my id:" + id);
        }
    }

    static class commonPeople implements Runnable {
        private int id;

        private CountDownLatch latch;

        public commonPeople(int id, CountDownLatch latch) {
            this.id = id;
            this.latch = latch;
        }

        @Override
        public void run() {
            try {
                latch.await();
                goOut();
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

        private void goOut() {
            System.out.println("I am common people! my id:" + id);
        }
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值