java多线程-快乐订座电影院

public class test{

public static void main(String[]args)
{
    //可用位置
    List available =new ArrayList();
    available.add(1);
    available.add(2);
    available.add(3);
    available.add(4);
    available.add(5);
    available.add(6);
    available.add(7);

    //顾客位置
    List seats1=new ArrayList();
    seats1.add(1);
    seats1.add(2);

    List seats2=new ArrayList();
    seats2.add(4);
    seats2.add(5);
    seats2.add(6);

    Cinema c=new Cinema(available,"happy");
    new Thread(new customer(c,seats1),"me").start();
    new Thread(new customer(c,seats2),"she").start();
}
}

class Cinema{
List available; //可用位置
String name;
public Cinema(List available,String name)
{
    this.available=available;
    this.name=name;
}

public boolean bookticks(List seats)
{
    System.out.println("可用位置:"+available);
    List copy=new ArrayList();
    copy.addAll(available);

    //去掉两个容器相同的元素
    copy.removeAll(seats);

    //判断是否选位置成功
    if(available.size()-copy.size()!=seats.size())
    {
        return false;
    }
    else
    {
        available=copy;
    }

    return true;
}

}

class customer implements Runnable{
Cinema cinema; //哪个影院
Listseats;  //多少个位置
public customer(Cinema cinema,List seats)
{
    this.cinema=cinema;
    this.seats=seats;
}

public void run()
{
    synchronized(cinema) {  //锁影院
    boolean flag=cinema.bookticks(seats);

    if(flag)
    {
        System.out.println("出票成功"+Thread.currentThread().getName()+"位置:"+seats);

    }else
    {
        System.out.println("出票失败"+Thread.currentThread().getName()+"位置不够");
    }
    }

}

}

分享标题:java多线程-快乐订座电影院
分享地址:http://myzitong.com/article/gdcgod.html