火车卖票
Ticket类(车票)
private Integer ticketNum; //票号
private String trainNum; //车次
private String Origin; //始发地
private String destination; //目的地
创建ticket
package cn.hp.train;
public class Ticket {
private Integer ticketNum;//票号
private String trainNum;//车次
private String Origin;//始发地
private String destination;//目的地
@Override
public String toString() {
return "票号:" + ticketNum +
", 车次:'" + trainNum + '\'' +
", 始发地:'" + Origin + '\'' +
", 目的地:'" + destination + '\'' ;
}
public Ticket(Integer ticketNum, String trainNum, String origin, String destination) {
this.ticketNum = ticketNum;
this.trainNum = trainNum;
Origin = origin;
this.destination = destination;
}
public Ticket() {
}
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;
}
}
创建ticketer
package cn.hp.train;
import java.util.List;
public class Ticketer extends Thread{
private List<Ticket> tickets;//票房(多个售票员同一个售票)
//卖票方法(卖一张从集合就要删一张票)
public void sellingTickets(){
Ticket ticket = this.tickets.remove(0);
System.out.println(this.getName()+"买了一张"+ticket);
}
@Override
public void run() {
while (true) {
//同一cpu,只有一个线程的锁,只能拿到一个
synchronized (this.tickets) {
if (this.tickets.size() > 0) {
sellingTickets();
} else {
System.out.println(this.getName() + "售完");
break;
}
}
}
}
@Override
public String toString() {
return "Ticketer{" +
"tickets=" + tickets +
'}';
}
public List<Ticket> getTickets() {
return tickets;
}
public void setTickets(List<Ticket> tickets) {
this.tickets = tickets;
}
}
测试类Test
package cn.hp.train;
import java.util.ArrayList;
import java.util.List;
public class Test {
public static void main(String[] args) {
//票房
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();
}
}