1 package cn.chapter4.test5;
2
3 public class SicknessDemo {
4
5 /**
6 * 模拟叫号看病
7 * @param args
8 *
9 * 思路:把普通号看病写在主线程里,特需号看病写在子线程里,当普通号看到第10个人之后,让
10 * 特需号的子线程强制执行,也就是在相应位置写一句 special.join()
11 */
12 public static void main(String[] args) {
13 // 创建特需号线程
14 MyThread special = new MyThread("特需号", 10, 3000);
15 // 修改主线程名称为普通号
16 Thread.currentThread().setName("普通号");
17 // 设置特需号线程优先级高,提高特需号叫到的概率
18 special.setPriority(8);
19 // 启动子线程,也就是特需号线程
20 special.start();
21 // 主线程普通号循环叫号看病
22 for (int i = 0; i < 20; i++) {
23 System.out.println(Thread.currentThread().getName() + ":" + (i + 1)
24 + "号病人在看病!");
25 // 普通号叫到第10个号,特需号线程强行执行,阻塞主线程
26 if (i == 9) {
27 try {
28 // 子线程(特需号线程)强行执行
29 special.join();
30 } catch (InterruptedException e) {
31 e.printStackTrace();
32 }
33 }
34 try {
35 // 普通号看病间隔时间
36 Thread.sleep(500);
37 } catch (InterruptedException e) {
38 e.printStackTrace();
39 }
40
41 }
42 }
43
44 }
45
46 class MyThread extends Thread {
47 private String name; // 线程名字
48 private int number;
49 private int time;
50
51 public MyThread(String name, int number, int time) {
52 super(name); // 调用THread类的构造方法,在创建线程对象时指定线程名
53 this.number = number;
54 this.time = time;
55 }
56
57 @Override
58 // run方法里模拟子线程特需号的看病过程
59 public void run() {
60 for (int i = 0; i < number; i++) {
61 System.out.println(this.getName() + ":" + (i + 1) + "号病人在看病!");// this是当前的线程对象
62 try {
63 // 设置特需号看病时间
64 Thread.sleep(time);
65 } catch (InterruptedException e) {
66 e.printStackTrace();
67 }
68 }
69
70 }
71
72 }