用Runnable接口程序来模拟航班售票系统
时间: 2023-12-14 07:36:48 浏览: 117
好的,我来给您展示一个简单的模拟航班售票系统的程序,使用Java中的Runnable接口实现多线程。
首先,我们需要定义一个Flight类来表示航班,包括航班号、起点城市、终点城市、出发时间、座位数等信息:
```java
public class Flight {
private String flightNo;
private String from;
private String to;
private Date departureTime;
private int seatNum;
// 构造函数
public Flight(String flightNo, String from, String to, Date departureTime, int seatNum) {
this.flightNo = flightNo;
this.from = from;
this.to = to;
this.departureTime = departureTime;
this.seatNum = seatNum;
}
// getter 和 setter 方法
// ...
}
```
然后,我们定义一个Ticket类来表示机票,包括航班号、座位号等信息:
```java
public class Ticket {
private String flightNo;
private int seatNo;
// 构造函数
public Ticket(String flightNo, int seatNo) {
this.flightNo = flightNo;
this.seatNo = seatNo;
}
// getter 和 setter 方法
// ...
}
```
接下来,我们定义一个FlightTicketSystem类来模拟航班售票系统,包括航班列表、机票列表等信息,并实现Runnable接口来模拟售票线程:
```java
public class FlightTicketSystem implements Runnable {
private List<Flight> flights;
private List<Ticket> tickets;
// 构造函数
public FlightTicketSystem(List<Flight> flights) {
this.flights = flights;
this.tickets = new ArrayList<>();
}
// 售票方法
public synchronized boolean sellTicket(String flightNo) {
Flight flight = null;
for (Flight f : flights) {
if (f.getFlightNo().equals(flightNo)) {
flight = f;
break;
}
}
if (flight == null || flight.getSeatNum() <= 0) {
return false;
}
Ticket ticket = new Ticket(flightNo, flight.getSeatNum());
flight.setSeatNum(flight.getSeatNum() - 1);
tickets.add(ticket);
System.out.println(Thread.currentThread().getName() + " sells ticket: " + ticket);
return true;
}
// run方法,模拟售票过程
@Override
public void run() {
while (true) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
int index = (int) (Math.random() * flights.size());
String flightNo = flights.get(index).getFlightNo();
if (!sellTicket(flightNo)) {
System.out.println(Thread.currentThread().getName() + " fails to sell ticket for flight " + flightNo);
}
}
}
}
```
最后,我们在主函数中创建多个线程来模拟售票过程:
```java
public class Main {
public static void main(String[] args) {
List<Flight> flights = new ArrayList<>();
flights.add(new Flight("CA001", "Beijing", "Shanghai", new Date(), 10));
flights.add(new Flight("CA002", "Shanghai", "Beijing", new Date(), 10));
flights.add(new Flight("CA003", "Beijing", "Guangzhou", new Date(), 10));
flights.add(new Flight("CA004", "Guangzhou", "Beijing", new Date(), 10));
flights.add(new Flight("CA005", "Shanghai", "Guangzhou", new Date(), 10));
flights.add(new Flight("CA006", "Guangzhou", "Shanghai", new Date(), 10));
FlightTicketSystem system = new FlightTicketSystem(flights);
Thread t1 = new Thread(system, "Seller A");
Thread t2 = new Thread(system, "Seller B");
Thread t3 = new Thread(system, "Seller C");
t1.start();
t2.start();
t3.start();
}
}
```
以上就是一个简单的航班售票系统的模拟程序,使用了Java中的Runnable接口来实现多线程。当线程在售票时,会随机选择一个航班并尝试售出一张机票,如果售票成功,会将机票信息打印出来;如果售票失败,会输出相应的提示信息。
阅读全文