废话不多说,直接上代码:
包含输入选座,判断选座,输出空座位等,使用Set 存储座位,synchronized 保护线程
/**
* Create with IDEA
*
* @author tyr
* @Date:2023/04/13/15:01
* @Description:
* 关于多线程电影院选位置的程序 采用了Set HashSet ,因为set不能重复,之前老师使用的是List可以重复,所以我做了修改,更加严谨一些,并且添加了inset方法任意选择座位,更加方便快捷。
**/
public class HappyC {
public static int count = 1;
public static int j = 1;
public static void main(String[] args){
Set<Integer> t = new HashSet<>();
for (int i = 1;i<=5;i++){
t.add(i);
}
System.out.println("一共创建了"+t.size()+"个序号座位");
Set<Integer> seats1 = new HashSet<>();
Set<Integer> seats2 = new HashSet<>();
insert(seats1);
insert(seats2);
Cinema c = new Cinema(t,"太平洋影院");
new Thread(new HappyCustomer(c,seats1),"tyr").start();
new Thread(new HappyCustomer(c,seats2),"xxx").start();
}
public static void insert(Set<Integer> list){
Scanner sc = new Scanner(System.in);
while(true){
System.out.print("顾客"+count+"请输入想要的第"+j+"个位置(0 end):");
int i = sc.nextInt();
if (i == 0){
System.out.println("顾客"+count+"结束订单");
j = 1;
break;
}
list.add(i);
j++;
System.out.println();
}
count++;
}
}
//顾客
class HappyCustomer implements Runnable{
Cinema cinema; //客户要去的电影院对象
Set<Integer> seats;
//构造函数传入要去的电影院 和 需要选择的座位,存入在seats Set里
public HappyCustomer(Cinema cinema, Set<Integer> seats) {
this.cinema = cinema;
this.seats = seats;
}
//重写线程入口
@Override
public void run() {
synchronized (cinema) { //为了线程的安全考虑,加入了synchronized锁,锁对象为cinema
boolean flag = cinema.bookTickets(seats);
if (flag) {
System.out.println(Thread.currentThread().getName() + " booked successful --- seats : " + seats);
} else {
System.out.println(Thread.currentThread().getName() + " booked fault --- no more seats");
}
}
}
}
//影院
class Cinema{
Set<Integer> available;//可用的位置
String name;//影院名称,我输出的时候没做输出,可以自行输出
public Cinema(Set<Integer> available,String name){
this.available = available;
this.name = name;
}
public boolean bookTickets(Set<Integer> seats){
System.out.println("可用位置为:"+available);
//保证源数据的安全,多创建了一个Set 实例对象
Set<Integer> copy = new HashSet<>(available);
copy.removeAll(seats);
if (available.containsAll(seats)){//判断你选择的位置是否都包含在电影院的空座位中
available = copy;
return true;
}else {
return false;
}
}
}
希望能为大家提供到借鉴意义,一起学习进步,加油!