java编程 现在有100张火车票,3个卖票窗口同时卖票,直至售空结束。请编写代码模拟此过程。
时间: 2023-05-22 09:01:23 浏览: 176
以下是 Java 代码模拟火车票售卖过程:
```java
public class TrainTicketSale {
public static void main(String[] args) {
int totalTickets = 100;
int ticketsSold = 0;
Object lock = new Object();
// 创建三个售票窗口
TicketSeller seller1 = new TicketSeller("窗口1", lock, totalTickets, ticketsSold);
TicketSeller seller2 = new TicketSeller("窗口2", lock, totalTickets, ticketsSold);
TicketSeller seller3 = new TicketSeller("窗口3", lock, totalTickets, ticketsSold);
// 启动售票窗口线程
seller1.start();
seller2.start();
seller3.start();
}
}
class TicketSeller extends Thread {
private String name;
private Object lock;
private int totalTickets;
private int ticketsSold;
public TicketSeller(String name, Object lock, int totalTickets, int ticketsSold) {
this.name = name;
this.lock = lock;
this.totalTickets = totalTickets;
this.ticketsSold = ticketsSold;
}
@Override
public void run() {
while (ticketsSold < totalTickets) {
synchronized (lock) {
if (ticketsSold < totalTickets) {
System.out.println(name + "售出第" + (++ticketsSold) + "张票");
}
}
}
}
}
```
以上代码中,TrainTicketSale 类是程序的入口,它创建了三个 TicketSeller 对象,每个对象代表一个售票窗口。TicketSeller 类继承自 Thread 类,它的 run() 方法模拟了售票过程。在 run() 方法中,每个售票窗口都会不断地尝试售出火车票,直到所有票都售完为止。为了保证线程安全,售票过程中使用了一个共享的锁对象 lock。
阅读全文