1 package demo7; 2 3 //三个人共抢10张票,限黄牛党只能抢一张票 4 public class MyThread7 implements Runnable { 5 private int count = 10; // 票数 6 private int num; // 抢到第几张票 7 8 public void run() { 9 10 while (true) { 11 sale(); 12 if(Thread.currentThread().getName().equals("黄牛党")) { 13 try { 14 Thread.sleep(10000); 15 } catch (InterruptedException e) { 16 e.printStackTrace(); 17 } 18 } 19 } 20 } 21 22 public synchronized void sale() { 23 if (count <= 0) { 24 return; 25 } 26 try { 27 Thread.sleep(200); 28 } catch (InterruptedException e) { 29 e.printStackTrace(); 30 } 31 System.out.println(Thread.currentThread().getName() + "抢到第" + (num + 1) + "张票,剩余" + (count - 1) + "张票"); 32 num++; 33 count--; 34 } 35 36 public static void main(String[] args) { 37 MyThread7 mt = new MyThread7(); 38 Thread t1 = new Thread(mt, "李明"); 39 Thread t2 = new Thread(mt, "黄牛党"); 40 Thread t3 = new Thread(mt, "吴勇"); 41 t1.start(); 42 t2.start(); 43 t3.start(); 44 45 } 46 }