多线程---模拟叫号看病

 1 //实现Runnable,编写VIP病人看病线程
 2 public class MyRunnable implements Runnable{
 3     private int num ; 
 4     public void run() {
 5         while(true) {
 6             if(num == 10) {
 7                 break;
 8             }
 9             try {
10                 Thread.sleep(1000);
11             } catch (InterruptedException e) {
12                 // TODO Auto-generated catch block
13                 e.printStackTrace();
14             }
15             System.out.println(Thread.currentThread().getName()+(num+1)+"号病人正在看病!");
16             num++;
17         }
18     }
19 }
实现Runnable,编写VIP病人看病线程
 1 //测试类,编写普通病人看病线程
 2 public class Test {
 3     public static void main(String[] args) {
 4         Thread.currentThread().setName("普通号:");
 5         MyRunnable vip = new MyRunnable();
 6         Thread thread = new Thread(vip,"特需号:");
 7         thread.start();
 8         int num = 0 ;
 9         while(true) {
10             if(num == 10) {
11                 try {
12                     thread.join();//中止普通病人的看病线程,由VIP病人线程先执行完
13                 } catch (InterruptedException e) {
14                     // TODO Auto-generated catch block
15                     e.printStackTrace();
16                 }
17             }
18             if(num>=50) {
19                 break;
20             }
21             try {
22                 Thread.sleep(500);
23             } catch (InterruptedException e) {
24                 // TODO Auto-generated catch block
25                 e.printStackTrace();
26             }
27             System.out.println(Thread.currentThread().getName()+(num+1)+"号正在看病!");
28             num++;
29         }
30     }
31 }
测试类,编写普通病人看病线程

运行结果:

 

posted on 2019-08-05 19:40  迪恩9  阅读(922)  评论(0编辑  收藏  举报