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 }