多線程---模擬叫號看病


 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 }
測試類,編寫普通病人看病線程

運行結果:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM