Java多线程学习——例子:模拟电影院抢座位
2024-09-05 17:06:30
Cinema——List<Integer>数据结构存储电影院座位
public class Cinema{
private List<Integer> seats; //剩余座位 public Cinema(List<Integer> seats) {
this.seats = seats;
} public boolean seatGrabbing(List<Integer> needTickets){ if(needTickets.size()>seats.size()){
return false;
}
synchronized (this) {
if(needTickets.size()>seats.size()){
return false;
}
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("剩余座位:" + seats);
List<Integer> tmpSeats=new ArrayList<Integer>();
tmpSeats.addAll(seats);
tmpSeats.removeAll(needTickets);
if(seats.size()-tmpSeats.size()==needTickets.size()){
seats=tmpSeats;
return true;
}else {
return false;
}
}
}
}
CinemaCustomer
public class CinemaCustomer implements Runnable {
private List<Integer> needTickets; //需要的票
private Cinema cinema;
private boolean isGetTickets=false; public CinemaCustomer(List<Integer> needTickets, Cinema cinema) {
this.needTickets = needTickets;
this.cinema = cinema;
} @Override
public void run() {
isGetTickets=cinema.seatGrabbing(needTickets);
if(isGetTickets){
System.out.println(Thread.currentThread().getName()+"抢票成功"+needTickets);
}else{
System.out.println("抢票失败"+needTickets);
}
}
}
GrabbingTickets
public class GrabbingTickets {
public static void main(String[] args) {
List<Integer> seats=new ArrayList<Integer>(); //总座位
seats.add(1);
seats.add(2);
seats.add(3);
seats.add(4);
seats.add(5);
Cinema cinema=new Cinema(seats); List<Integer> seat1=new ArrayList<Integer>();
seat1.add(1);
seat1.add(2); List<Integer> seat2=new ArrayList<Integer>();
seat2.add(5);
seat2.add(4); new Thread(new CinemaCustomer(seat1,cinema),"Tom").start();
new Thread(new CinemaCustomer(seat2,cinema),"Job").start();
}
}
很简单的一个例子,但是体会到了线程同步,也学会使用容器的一些常用方法。
最新文章
- Selenium2学习-040-JavaScript弹出框(alert、confirm、prompt)操作演示实例
- hashMap的get()方法,错用并发造成cpu和负载高
- unity中三种调用其他脚本函数的方法
- NPOI2.0学习(三)
- canvas 实现 柱状图
- Intellij快捷键
- MVC4相关Razor语法以及Form表单
- python实现树莓派生成并识别二维码
- phpstorm9整合本地apache和豆沙绿主题设置(附资源)
- Eclipse之JSON导包
- Win10系统盘制作及安装流程
- mount --bind使用方法
- Linux - 利用systemctl命令管理服务
- SSL踩坑ERR_SSL_VERSION_OR_CIPHER_MISMATCH
- Redis备份及回收策略
- C#零基础入门04:打老鼠初级之枚举、重构、事件处理器
- 启动ECLIPSE时,提示找到不 eclipse\jre\bin\javaw.exe
- 修改类不用重启Tomcat加载整个项目
- 如何运行.ipynb文件
- STC51六中中断配置点亮一个LED