Java模拟车站售票系统。用多线程模拟火车站售票大厅的情形,包括:添加顾客、顾客离开、增加售票窗口、关闭售票窗口功能代码
时间: 2023-07-10 12:16:57 浏览: 38
好的,下面是Java模拟车站售票系统的示例代码,包括添加顾客、顾客离开、增加售票窗口、关闭售票窗口功能的实现:
```java
import java.util.LinkedList;
import java.util.Queue;
public class TrainTicketSystem {
private int customerCount; // 顾客数量
private int windowCount; // 售票窗口数量
private Queue<Customer> customerQueue; // 顾客队列
public TrainTicketSystem(int windowCount) {
this.customerCount = 0;
this.windowCount = windowCount;
this.customerQueue = new LinkedList<>();
}
// 添加顾客
public synchronized void addCustomer(Customer customer) {
this.customerQueue.add(customer);
this.customerCount++;
System.out.println("顾客" + customer.getId() + "加入队列,当前队列长度:" + this.customerCount);
}
// 顾客离开
public synchronized void removeCustomer() {
Customer customer = this.customerQueue.poll();
if (customer != null) {
this.customerCount--;
System.out.println("顾客" + customer.getId() + "已离开队列,当前队列长度:" + this.customerCount);
}
}
// 增加售票窗口
public synchronized void addWindow() {
this.windowCount++;
System.out.println("增加售票窗口,当前窗口数量:" + this.windowCount);
}
// 关闭售票窗口
public synchronized void removeWindow() {
if (this.windowCount > 0) {
this.windowCount--;
System.out.println("关闭售票窗口,当前窗口数量:" + this.windowCount);
}
}
}
class Customer {
private int id; // 顾客ID
private int buyCount; // 购票数量
private long time; // 乘车时间
public Customer(int id, int buyCount, long time) {
this.id = id;
this.buyCount = buyCount;
this.time = time;
}
public int getId() {
return id;
}
public int getBuyCount() {
return buyCount;
}
public long getTime() {
return time;
}
}
```
在上面的代码中,TrainTicketSystem类表示车站售票系统,其中包括添加顾客、顾客离开、增加售票窗口、关闭售票窗口等功能的实现。Customer类表示顾客,包括顾客ID、购票数量、乘车时间等属性。使用Queue来实现顾客队列的管理,使用synchronized关键字来实现多线程同步。