场景:一个会议,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(); } }