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();
}
}

很简单的一个例子,但是体会到了线程同步,也学会使用容器的一些常用方法。

最新文章

  1. Selenium2学习-040-JavaScript弹出框(alert、confirm、prompt)操作演示实例
  2. hashMap的get()方法,错用并发造成cpu和负载高
  3. unity中三种调用其他脚本函数的方法
  4. NPOI2.0学习(三)
  5. canvas 实现 柱状图
  6. Intellij快捷键
  7. MVC4相关Razor语法以及Form表单
  8. python实现树莓派生成并识别二维码
  9. phpstorm9整合本地apache和豆沙绿主题设置(附资源)
  10. Eclipse之JSON导包
  11. Win10系统盘制作及安装流程
  12. mount --bind使用方法
  13. Linux - 利用systemctl命令管理服务
  14. SSL踩坑ERR_SSL_VERSION_OR_CIPHER_MISMATCH
  15. Redis备份及回收策略
  16. C#零基础入门04:打老鼠初级之枚举、重构、事件处理器
  17. 启动ECLIPSE时,提示找到不 eclipse\jre\bin\javaw.exe
  18. 修改类不用重启Tomcat加载整个项目
  19. 如何运行.ipynb文件
  20. STC51六中中断配置点亮一个LED

热门文章

  1. Codeforces 911 三循环数覆盖问题 逆序对数结论题 栈操作模拟
  2. 牛客OI周赛13-提高组 比赛总结
  3. Spring IOC -bean对象的生命周期详解
  4. vscode sftp插件的使用
  5. jquery easyui datagrid 远程加载数据----把主键渲染为值遇到的问题及解决方案
  6. thinkphp5杂谈--模板
  7. 《转》从系统和代码实现角度解析TensorFlow的内部实现原理 | 深度
  8. js-点击tab按钮,同一页面显示不同的内容
  9. linux 下u盘只读
  10. java总结1