一:引言
这里是加了个同步块,来保证数据的准确性,用了个容器使,我们可以选位置
二:上码(这里是模拟在电影院选位置)
package com.wyj.three;
import java.util.ArrayList;
import java.util.List;
public class Demo6_快乐影院2 {
public static void main(String[] args) {
// TODO Auto-generated method stub
//电影院中可用的位置
List<Integer> ticts = new ArrayList<>();
ticts.add(1);
ticts.add(2);
ticts.add(3);
ticts.add(4);
ticts.add(5);
ticts.add(6);
//顾客需要的位置
List<Integer> seats1 = new ArrayList<>();
seats1.add(1);
seats1.add(2);
List<Integer> seats2 = new ArrayList<>();
seats2.add(7);
Cinema2 cinema = new Cinema2(ticts,"快乐影院!");
new Thread(new Customer2(seats1, cinema),"大王").start();
new Thread(new Customer2(seats2,cinema),"小王").start();
}
}
class Cinema2{
private List<Integer> ticts;//票数
private String name;//电影院名称
public Cinema2(List<Integer> ticts, String name) {
super();
this.ticts = ticts;
this.name = name;
}
//购票
public boolean Moreticket(List<Integer> seats) {
System.out.println("可用位置为:"+this.ticts);
List<Integer> copy = new ArrayList<Integer>();
//赋值,将ticte容器的内容复制到copy容器当中
copy.addAll(ticts);
//相减 这样可以减去copy容器包含seats容器中相同的元素
copy.removeAll(seats);
//这里表示 seats容器当中的元素,copy容器都包含
if(ticts.size() - copy.size() != seats.size()) {
return false;
}
ticts = copy;
return true;
}
}
//顾客 自己选位置
class Customer2 implements Runnable{
private List<Integer> seats;
private Cinema2 ca;
public Customer2(List<Integer> seats, Cinema2 ca) {
super();
this.seats = seats;
this.ca = ca;
}
@Override
public void run() {
// TODO Auto-generated method stub
synchronized (ca) {
boolean flag = ca.Moreticket(seats);
if(flag) {
System.out.println("出票成功:"+Thread.currentThread().getName()+"的位置-->"+this.seats);
}else {
System.out.println("出票失败"+Thread.currentThread().getName());
}
}
}
}
如有疑问请留言