import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.Vector;
/**
* @Author: MiaoXiaoQiang
* @Date: 2021/8/21 16:23
*
* synchronized this 锁住对象,因为是对一个对象的多次操作
*/
public class ExerciseTransfer {
public static void main(String[] args) throws InterruptedException {
//模拟多人买票
TicketWindow ticketWindow = new TicketWindow(10000);
//为了让所有线程运行结束后再统计相关结果 需要对线程进行相关的控制
List<Thread> threadList = new ArrayList<>();
//售出票数总和
List<Integer> amountList = new Vector<>();
for (int i = 0; i <2000 ; i++) {
Thread thread = new Thread(()->{
//买票
int amount = ticketWindow.sell(randomAmount());
amountList.add(amount);
});
threadList.add(thread);
thread.start();
}
for (Thread thread : threadList) {
thread.join();
}
//统计相关票数
System.out.println("剩余票数:" + ticketWindow.getCount());
System.out.println("售出票数:" + amountList.stream().mapToInt(i->i).sum());
}
//Random 为线程安全
static Random random = new Random();
//随机购买票数 随机 1-5
public static int randomAmount(){
return random.nextInt(5) + 1;
}
}
class TicketWindow{
//成员变量
private int count;
//有参构造方法
public TicketWindow(int count){
this.count = count;
}
//get方法 获取剩余票数量
public int getCount(){
return count;
}
//售票
public synchronized int sell(int amount){
if (this.count >= amount){
this.count -= amount;
return amount;
} else {
return 0;
}
}
}
多线程之售票问题
最新推荐文章于 2022-12-16 11:51:47 发布