多线程快乐电影院

import java.util.ArrayList;
import java.util.List;

public class happymov {

    public static void main(String[] args) {
    //可用位置
        List<Integer> availzle=new ArrayList<Integer>();
        availzle.add(1);
        availzle.add(2);
        availzle.add(5);
        availzle.add(8);
        availzle.add(7);
        availzle.add(9);
        List<Integer> seat1=new ArrayList<Integer>();
        seat1.add(1);
        seat1.add(2);
        List<Integer> seat2=new ArrayList<Integer>();
        seat2.add(5);
        seat2.add(10);
        SxtCient s =new SxtCient(availzle,"happy sxt");
        new Thread(new HappyCustomer(s,seat1),"老王").start();
        new Thread(new HappyCustomer(s,seat2),"老还").start();
        
        
    }

}
class SxtCient{
    List <Integer> available;//可用位置
    String name;
    public SxtCient(List<Integer> available, String name) {
        super();
        this.available = available;
        this.name = name;
    }
    //购票
    public boolean bookTickets(List<Integer>seats) {
        System.out.println("可用位置为:"+available);
        List<Integer> copy =new ArrayList<Integer>();
        copy.addAll(available);
        //相减
        copy.removeAll(seats);
        //判断大小
        if(available.size()-copy.size()!=seats.size()) {
            return false;
            
        }
        //成功
        available=copy;
        return true;
        
        
        
    }
    
}

class HappyCustomer implements Runnable{
    SxtCient sxtCient;
    List <Integer> seats;
    public HappyCustomer(SxtCient sxtCient, List<Integer> seats) {
        super();
        this.sxtCient = sxtCient;
        this.seats = seats;
    }
    
    @Override
    public void run() {
        synchronized (sxtCient) {
            boolean flag= sxtCient.bookTickets(seats); 
        
        if(flag) {
            System.out.println("出票成功"+Thread.currentThread().getName()+"-->位置为"+seats);
        }else {
            System.out.println("出票失败"+Thread.currentThread().getName()+"-->位置不够");
        }
    }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值