import java.util.List;
public class Ticketer extends Thread {
private List<Ticket> tickets;//票库(多个售票员同一个票库)
public void sellingTickets() {
Ticket ticket = tickets.remove(0);
System.out.println(this.getName() + "买了一张" + ticket);
}
@Override
public void run() {
synchronized (this.tickets) {
int n = tickets.size();
while (true) {
if (this.tickets.size() > 0) {
sellingTickets();
} else {
System.out.println(this.getName() + ":票已售完");
break;
}
}
}
}
public void setTickets(List<Ticket> tickets) {
this.tickets = tickets;
}
}
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 "" +
"票=" + ticketNum +
", 航班=" + trainNum + '\'' +
", 开始地点=" + Origin + '\'' +
" -->终点=" + destination + '\'' +
'}';
}
}
import java.util.ArrayList;
import java.util.List;
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();
}
}