|--需求說明java
|--實現方式網絡
在run()方法裏面寫一個while循環,循環體裏面執行一個加過synchronized的方法,這個方法下面加一個判斷語句,當線程名爲「黃牛黨」的時候,退出這個線程ide
|--代碼內容 this


1 package cn.thread1; 2 3 import java.util.Enumeration; 4 5 /** 6 * @auther::9527 7 * @Description: 看病 8 * @program: shi_yong 9 * @create: 2019-08-05 14:34 10 */ 11 public class Patient implements Runnable { 12 private String name; 13 private int num = 0; //搶的票 14 private int count = 10; //總票數 15 private boolean flag = false; //記錄票是否買完 16 17 public Patient() { 18 } 19 20 public Patient(String name) { 21 this.name = name; 22 } 23 24 @Override 25 public void run() { 26 while (!flag) { 27 tickets(); 28 //若是黃牛黨搶票,就退出循環 29 if (Thread.currentThread().getName().equals("黃牛黨")){ 30 return; 31 } 32 } 33 34 } 35 36 public synchronized void tickets() { 37 //設置循環終止條件 38 if (count <= 0) { 39 flag = true; 40 return; 41 } 42 //每循環一次,總票數減一,搶到的票數加一 43 count--; 44 num++; 45 try { 46 //模擬網絡延遲 47 Thread.sleep(100); 48 } catch (InterruptedException e) { 49 e.printStackTrace(); 50 } 51 //按需求輸出信息 52 System.out.println(Thread.currentThread().getName()+"搶到了第"+num+"張票,剩餘"+count+"張票!"); 53 54 } 55 }


1 package cn.thread1; 2 3 /** 4 * @auther::9527 5 * @Description: 運行 6 * @program: shi_yong 7 * @create: 2019-08-05 15:00 8 */ 9 public class Main { 10 public static void main(String[] args) { 11 Patient p = new Patient(); 12 13 Thread t1 = new Thread(p,"桃跑跑"); 14 Thread t2 = new Thread(p,"張票票"); 15 Thread t3 = new Thread(p,"黃牛黨"); 16 t1.start(); 17 t2.start(); 18 t3.start(); 19 } 20 }
|--運行結果spa
|--錯誤記錄線程
最開開始的時候,判斷搶票人的方法寫在run()方法外面,一直沒有實現需求,3d
以下所示,若是判斷在輸出信息前,就會致使票沒搶完就程序終止code