需求:
1 package GouPiao; 2 3 /** 4 * 模拟网络延时线程不安全 5 */ 6 public class Site implements Runnable { 7 private int count = 10; // 记录剩余票数 8 private int num = 0; // 记录买到第几张票 9 private boolean flag = false; //记录是否售完 10 11 public void run() { 12 while (true) { 13 if(!sale()){ 14 break; 15 } 16 } 17 } 18 // 同步方法:卖票 19 public synchronized boolean sale() { 20 if (count <= 0) { 21 return false; 22 } 23 // 第一步:修改数据 24 num++; 25 count--; 26 try { 27 Thread.sleep(500); // 模拟网络延时 28 } catch (InterruptedException e) { 29 e.printStackTrace(); 30 } 31 // 第二步:显示信息 32 System.out.println(Thread.currentThread().getName() + "抢到第" + num 33 + "张票,剩余" + count + "张票!"); 34 if(Thread.currentThread().getName().equals("黄牛党")){ 35 return false; 36 } 37 return true; 38 39 } 40 }
1 package GouPiao; 2 /* 3 *测试类 4 * 5 */ 6 7 public class Test { 8 public static void main(String[] args) { 9 Site site = new Site(); 10 Thread person1= new Thread(site,"桃跑跑"); 11 Thread person2= new Thread(site,"张票票"); 12 Thread person3= new Thread(site,"黄牛党"); 13 person1.start(); 14 person2.start(); 15 person3.start(); 16 } 17 }
运行结果: