1,站台类(假设只有一个站台)
package com.cn.thread.ticket; import com.cn.thread.people.People; import java.util.concurrent.atomic.AtomicInteger; /** * Created by lizhihao on 2019/5/19 15:48 */ public class Station { public static volatile AtomicInteger ticketAmount = new AtomicInteger(100);//总票数 //买票 public static synchronized int bugTicket(String peopleName){ if(Station.ticketAmount.get()==0){ System.out.println("尊敬的"+peopleName+":非常抱歉,票已经卖完了!"); return 0; } int i = subTicket(); System.out.println(peopleName+"买了"+1+"张票,"+i); return i; } //卖票 每次卖一张票,返回剩余票数量 public static int subTicket(){ System.out.println("站台开始卖票了,此时还剩下:"+ ticketAmount.get()+"张票!"); if(ticketAmount.get()>0) ticketAmount.getAndDecrement(); else System.out.println("票已经卖完了。。。"); return ticketAmount.get(); } public static void main(String[] args) { for (int i=0;i<101;i++){ Thread peopleA = new People("第"+(i+1)+"个用户"); peopleA.start(); } } }
2,人员类,模拟买票
package com.cn.thread.people; import com.cn.thread.ticket.Station; /** * Created by lizhihao on 2019/5/19 16:09 */ public class People extends Thread{ String peopleName; public People(String peopleName){ this.peopleName = peopleName; } @Override public void run() { bugTicket(); } //买票 public void bugTicket(){ Station.bugTicket(this.peopleName); } }