模拟火车站窗口售票,三个窗口同时对外发售1000张火车票,避免出现一票多卖的情况即一个窗口售票过程中,其他窗口无法对余票进行操作,Java代码
时间: 2023-07-19 20:29:51 浏览: 45
下面是一个简单的Java代码示例来模拟火车站窗口售票。
```java
public class TrainTicketSeller {
private static final int TOTAL_TICKETS = 1000;
private static int remainingTickets = TOTAL_TICKETS;
public static synchronized int sellTickets(int tickets) {
if (tickets > remainingTickets) {
return -1; // 剩余票数不足
}
remainingTickets -= tickets;
return remainingTickets;
}
}
public class TicketSellerThread extends Thread {
private int ticketsToSell;
public TicketSellerThread(int ticketsToSell) {
this.ticketsToSell = ticketsToSell;
}
@Override
public void run() {
int remainingTickets = TrainTicketSeller.sellTickets(ticketsToSell);
if (remainingTickets == -1) {
System.out.println("窗口 " + Thread.currentThread().getName() + " 售票失败:剩余票数不足");
} else {
System.out.println("窗口 " + Thread.currentThread().getName() + " 成功售出 " + ticketsToSell + " 张票,剩余票数:" + remainingTickets);
}
}
}
public class Main {
public static void main(String[] args) {
TicketSellerThread seller1 = new TicketSellerThread(300);
TicketSellerThread seller2 = new TicketSellerThread(400);
TicketSellerThread seller3 = new TicketSellerThread(300);
seller1.start();
seller2.start();
seller3.start();
}
}
```
`TrainTicketSeller` 类是售票系统的核心代码,使用 `synchronized` 保证了在一个窗口售票时,其他窗口无法对余票进行操作。
`TicketSellerThread` 类继承自 `Thread`,每个线程代表一个窗口,执行售票操作。
`Main` 类启动了三个线程,分别代表三个窗口,每个窗口售出一定数量的票。在运行过程中,售票系统会自动锁定余票数量,避免出现一票多卖的情况。