import java.util.ArrayList;
import java.util.List;
public class HappyCinema {
public static void main(String[] args) {
//可用位置
List<Integer> avilable = new ArrayList<Integer>();
for (int i = 1; i <= 5; i++) {
avilable.add(i);
}
//顾客1选的座位
List<Integer> seat = new ArrayList<>();
seat.add(1);
seat.add(3);
seat.add(5);
//顾客2选的座位
List<Integer> seat1 = new ArrayList<>();
seat1.add(4);
seat1.add(2);
seat1.add(3);
//电影院
Cinema cinema = new Cinema(avilable, "快乐影院");
Thread t1 = new Thread(new Customer(seat, cinema), "老高");
Thread t2 = new Thread(new Customer(seat1, cinema), "老王");
t1.start();
t2.start();
}
}
class Customer implements Runnable{
private List<Integer> seat;//选的座位
private Cinema cinema;//选的电影院
Customer(List<Integer> seat, Cinema cinema) {
this.seat = seat;
this.cinema = cinema;
}
@Override
public void run() {
//同步代码块,锁定的是cinema
synchronized(cinema){
boolean flag =cinema.bookTicket(seat);
if(flag == false){
System.out.println("出票失败");
}else{
System.out.println("出票成功");
}
}
}
}
class Cinema{
private List<Integer> avilable; //显示可用的位置
private String name;//电影院名称
Cinema(List<Integer> avilable, String name) {
this.avilable = avilable;
this.name = name;
}
//购票
public boolean bookTicket(List<Integer> seat){
System.out.println("当前可用的位置为:" + this.avilable + Thread.currentThread().getName()+ "要取走位置 --->" + seat );
List<Integer> copy = new ArrayList<Integer>();
copy.addAll(avilable);
copy.removeAll(seat);
if(avilable.size()-copy.size() != seat.size())
return false;
//如果成功,则赋值
avilable = copy;
return true;
}
}
运行结果:
当前可用的位置为:[1, 2, 3, 4, 5]老高要取走位置 --->[1, 3, 5]
出票成功
当前可用的位置为:[2, 4]老王要取走位置 --->[4, 2, 3]
出票失败