线程---同步---快乐影院小案例

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]
出票失败

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值