10-案例实现
案例实现
根据如下步骤实现本案例。
1.创建一个名为 Videoconference
的类,并实现 Runnable
接口。该类将实现整个视频会议系统:
public class Videoconference implements Runnable {
2.声明一个 CountDownLatch
类型的名为 controller
的属性:
private final CountDownLatch controller;
3.实现类的构造器,对 CountDownLatch
的属性进行初始化。将 Videoconference
类等待的与会者数量作为参数:
public Videoconference(int number) {
controller=new CountDownLatch(number);
}
4.实现 arrive()
方法。视频会议的每个与会者抵达时,都将调用一次该方法。这个方法接收一个 String
类型的参数 name
——它表示与会者的姓名:
public void arrive(String name){
5.在该方法内部,输出从参数中接收到的与会者姓名:
System.out.printf("%s has arrived.",name);
6.调用 CountDownLatch
对象的 countDown()
方法:
controller.countDown();
7.调用 CountDownLatch
对象的 getCount()
方法,得到还需等待的与会人员数量,并输出该信息:
System.out.printf("VideoConference: Waiting for %d
participants.\n",controller.getCount());
8.实现视频会议系统的主要方法 run()
,它是所有 Runnable
对象必须有的:
@Override
public void run() {
9.调用 CountDownLatch
对象的 getCount()
方法,获取并输出与会人员的数量:
System.out.printf("VideoConference: Initialization: %d
participants.\n",controller.getCount());
10.用 CountDownLatch
对象的 await()
方法[1]等待与会人员全部抵达。因为该方法会抛出 InterruptedException
异常,所以需要进行异常处理:
try {
controller.await();
11.在所有与会者全部抵达时,输出一条提示信息:
System.out.printf("VideoConference: All the participants have
come\n");
System.out.printf("VideoConference: Let's start...\n");
} catch (InterruptedException e) {
e.printStackTrace();
}
12.创建一个名为 Participant
的类,并实现 Runnable
接口,它代表视频会议中的每个与会人员:
public class Participant implements Runnable {
13.声明一个私有的 Videoconference
类型的属性,并将其命名为 conference
:
private Videoconference conference;
14.声明一个私有的 String
类型的 name
的属性:
private String name;
15.在类的构造器中,对刚才声明的两个属性进行初始化:
public Participant(Videoconference conference, String name) {
this.conference=conference;
this.name=name;
}
16.实现与会人员的 run()
方法:
@Override
public void run() {
17.使当前线程随机休眠一段时间:
long duration=(long)(Math.random()*10);
try {
TimeUnit.SECONDS.sleep(duration);
} catch (InterruptedException e) {
e.printStackTrace();
}
18.调用 Videoconference
对象的 arrive()
方法,这表示一个与会者已到达:
conference.arrive(name);
19.实现应用程序的入口,创建包含 main()
方法的 Main
类:
public class Main {
public static void main(String[] args) {
20.创建一个 Videoconference
类型的变量 conference
。初始化参数为10,表示共有10个与会者:
Videoconference conference=new Videoconference(10);
21.创建并启动一个线程,用来执行 Videoconference
对象:
Thread threadConference=new Thread(conference);
threadConference.start();
22.循环创建并启动10个线程,用来执行不同的与会者对象:
for (int i=0; i<10; i++){
Participant p=new Participant(conference, "Participant "+i);
Thread t=new Thread(p);
t.start();
}