Java 多线程练习 医生看病

|--需求说明

|--实现思路

创建一个线程类,用来实现特需病人,优先等级最高,把main方法的线程取名为普通病人,详情见代码注释

|--代码内容

 1 package cn.doctor;
 2 
 3 /**
 4  * @auther::9527
 5  * @Description: 医生
 6  * @program: shi_yong
 7  * @create: 2019-08-05 20:12
 8  */
 9 public class Doctor {
10     public static void main(String[] args) throws InterruptedException {
11         //通过构造方法传参,特殊病人看一个300秒,总共10个特殊病人
12         SeeDoctor sd = new SeeDoctor(300, 10);
13         //给线程类取名为特需病人
14         Thread t = new Thread(sd,"特需病人");
15         //为主线程取名为普通病人
16         Thread.currentThread().setName("普通病人");
17         //启动特殊病人的线程
18         t.start();
19         //设置特殊病人的优先等级为最高
20         t.setPriority(10);
21         //启动普通病人的线程
22         for (int i = 0; i < 50; i++) {
23             
24             System.out.println("正在给第"+(i+1)+"位"+Thread.currentThread().getName()+"看病");
25             if (i == 9) {
26                 try {
27                     t.join();
28                 } catch (InterruptedException e) {
29                     e.printStackTrace();
30                 }
31             }
32         }
33     }
34 }
程序入口
线程类-特殊病人
 1 package cn.doctor;
 2 
 3 /**
 4  * @auther::9527
 5  * @Description: 线程类--看病
 6  * @program: shi_yong
 7  * @create: 2019-08-05 20:07
 8  */
 9 public class SeeDoctor implements Runnable {
10 private int time;  //看病花费的时间
11 private int num;  //看病的数量
12 
13     public SeeDoctor() {
14     }
15 
16     public SeeDoctor(int time, int num) {
17         this.time = time;
18         this.num = num;
19     }
20 
21     public int getTime() {
22         return time;
23     }
24 
25     public void setTime(int time) {
26         this.time = time;
27     }
28 
29     public int getNum() {
30         return num;
31     }
32 
33     public void setNum(int num) {
34         this.num = num;
35     }
36 
37     @Override
38     public void run() {
39         for (int i = 0; i < num; i++) {
40             System.out.println("正在给第"+(i+1)+"位"+ Thread.currentThread().getName()+"看病");
41             try {
42                 Thread.sleep(time);
43             } catch (InterruptedException e) {
44                 e.printStackTrace();
45             }
46         }
47 
48 
49     }
50 }

|--运行结果

猜你喜欢

转载自www.cnblogs.com/twuxian/p/11305434.html