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(); } }
很简单的一个例子,但是体会到了线程同步,也学会使用容器的一些常用方法。