多线程编程(2)等待多个并发事件的完成 CountDownLatch

场景:一个会议,10个参与者同时出发,

到达会议室时间不一致,会议需要10个人都到达才开始

 

1,视频会类

/**
 * 视频会类
 * 使用倒计时闩来控制所有参与者都到达后才发生事件
 */
public class VideoConference implements Runnable {
    /**
     * 倒计时闩对象
     */
    private final CountDownLatch controller;

    /**
     * 构造函数,初始化倒计时闩
     * @param number 参与者人数
     */
    public VideoConference(int number) {
        controller = new CountDownLatch(number);
    }

    /**
     * 每个参与到视频会议的都会调用此方法
     * @param name 参与者
     */
    public void arrive(String name) {
        System.out.printf("%s has arrived.\n", name);
        controller.countDown();
        System.out.printf("VideoConference: Waiting for %d participants.\n", controller.getCount());
    }

    /**
     * 核心方法,当所有参与者都到达了,就开始视频仁义
     */
    @Override
    public void run() {
        System.out.printf("VideoConference: Initialization: %d participants.\n", controller.getCount());
        try {
            // 等待所欲参与者
            controller.await();
            // 会议开始
            System.out.printf("VideoConference: All the participants have come\n");
            System.out.printf("VideoConference: Let's start...\n");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

2,参与者类

/**
 * 参与者类
 */
public class Participant implements Runnable {
    /**
     * 视频会议对象
     */
    private VideoConference conference;
    /**
     * 参与者的名称(仅仅是为了记录使用)
     */
    private String name;

    /**
     * 构造函数
     *
     * @param conference 视频会议对象
     * @param name       参与者的名称
     */
    public Participant(VideoConference conference, String name) {
        this.conference = conference;
        this.name = name;
    }


    /**
     * 核心方法,等待一个随机时间就进入视频会议
     */
    @Override
    public void run() {
        long duration = (long) (Math.random() * 10);
        try {
            TimeUnit.SECONDS.sleep(duration);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        conference.arrive(name);
    }
}

3,调用测试类

public static void main(String[] args) {
    // 创建一个视频会议对象,它有10个参与者
    VideoConference conference = new VideoConference(10);
    // 创建一个线程去运行视频会议
    Thread threadConference = new Thread(conference);
    threadConference.start();

    // 创建十个参与者,每个参与者在一个单独的线程中运行
    for (int i = 0; i < 10; i++) {
        Participant p = new Participant(conference, "Participant " + i);
        Thread t = new Thread(p);
        t.start();
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值