package com.zl.byticket;
import java.util.ArrayList;
import java.util.List;
public class ByTicket {
public static void main(String[] args) {
List<Integer> cinemaList = new ArrayList<Integer>();
cinemaList.add(1);
cinemaList.add(2);
cinemaList.add(3);
cinemaList.add(7);
cinemaList.add(11);
cinemaList.add(9);
cinemaList.add(5);
cinemaList.add(30);
Cinema cinema = new Cinema(cinemaList, "太平洋影院");
List<Integer> c1List = new ArrayList<>();
c1List.add(1);
c1List.add(11);
c1List.add(30);
Thread c1 = new Thread(new Customer(c1List, cinema), "何老板");
c1.start();
List<Integer> c2List = new ArrayList<>();
c2List.add(1);
c2List.add(30);
Thread c2 = new Thread(new Customer(c2List, cinema), "王小皮");
c2.start();
}
}
package com.zl.byticket;
import java.util.ArrayList;
import java.util.List;
public class Cinema {
private List<Integer> availableSeats;
private String name;
public Cinema(List<Integer> availableSeats, String name) {
super();
this.availableSeats = availableSeats;
this.name = name;
}
public boolean saleTickets(List<Integer> seats) {
System.out.println("现剩余的座位为:" + availableSeats);
List<Integer> copyList = new ArrayList<Integer>();
copyList.addAll(availableSeats);
copyList.removeAll(seats);
if ((availableSeats.size() - copyList.size()) != seats.size()) {
return false;
}
availableSeats = copyList;
return true;
}
}
package com.zl.byticket;
import java.util.List;
public class Customer implements Runnable {
List<Integer> seats;
Cinema cinema;
public Customer(List<Integer> seats, Cinema cinema) {
this.seats = seats;
this.cinema = cinema;
}
@Override
public void run() {
synchronized (cinema) {
boolean flag = cinema.saleTickets(seats);
if (flag) {
System.out.println("购票成功 " + Thread.currentThread().getName() + "购买的位置为:" + seats);
} else {
System.out.println("购票失败 " + Thread.currentThread().getName() + "购买失败");
}
}
}
}