public class Ticketer extends Thread{
private List<Ticket> tickets;//票库(多个售票员同一个票库)
public List<Ticket> getTickets() {
return tickets;
}
public void setTickets(List<Ticket> tickets) {
this.tickets = tickets;
}
//卖票方法(从集合中删除一张票)
//从票库删除一张票
static Object object = new Object();
public void sellingTickets(Object obj){
for(int i = 0;i < tickets.size(); i++){
if (obj == tickets.get(i))
{
tickets.remove(obj);
}
}
}
//重写Thread线程类的run方法
//实现多线程卖票,“卖完为止”
//如果剩余有票,则调用卖票方法
//否则,票已售完
@Override
public void run() {
int i = tickets.size();
try {
while (true){
//线程休眠
Thread.sleep(1000);
//线程同步
synchronized (object){
if (i > 0){
sellingTickets(i);
System.out.println("卖出的" + i + "号票" + Thread.currentThread().getName());
i--;
}else {
System.out.println("你需要的票已售完");
break;
}
}
}
}catch (Exception e) {
e.printStackTrace();
}
}
public class Ticket {
private Integer ticketNum; //票号
private String trainNum; //车次
private String Origin; //始发地
private String destination; //目的地
public Ticket() {
}
public Ticket(Integer ticketNum, String trainNum, String origin, String destination) {
this.ticketNum = ticketNum;
this.trainNum = trainNum;
Origin = origin;
this.destination = destination;
}
public Integer getTicketNum() {
return ticketNum;
}
public void setTicketNum(Integer ticketNum) {
this.ticketNum = ticketNum;
}
public String getTrainNum() {
return trainNum;
}
public void setTrainNum(String trainNum) {
this.trainNum = trainNum;
}
public String getOrigin() {
return Origin;
}
public void setOrigin(String origin) {
Origin = origin;
}
public String getDestination() {
return destination;
}
public void setDestination(String destination) {
this.destination = destination;
}
@Override
public String toString() {
return "Ticket{" +
"ticketNum=" + ticketNum +
", trainNum='" + trainNum + '\'' +
", Origin='" + Origin + '\'' +
", destination='" + destination + '\'' +
'}';
}
}
public class Test {
public static void main(String[] args) {
Ticketer t = new Ticketer();
//票库
List<Ticket> tickets = new ArrayList<>();
for (int i = 1; i <= 20 ; i++) {
Ticket ticket = new Ticket(i,"G2022","郑州","杭州");
tickets.add(ticket);
}
Ticketer t1 = new Ticketer();
t1.setName("小红");
Ticketer t2 = new Ticketer();
t2.setName("小明");
//给两个售票员设置同一个票库
t1.setTickets(tickets);
t2.setTickets(tickets);
//开始子线程进行售票
t1.start();
t2.start();
}
}