用JAVA制作模拟取钱排队
时间: 2024-10-26 13:17:37 浏览: 29
在Java中,你可以使用线程、队列和同步机制来创建一个简单的模拟取钱排队系统的模型。以下是一个基本的示例,展示了如何使用`ConcurrentLinkedQueue`来存储排队的人,以及如何使用多个线程代表银行柜员处理请求:
```java
import java.util.concurrent.*;
public class BankQueueSimulation {
private final int numATMs;
private final ConcurrentLinkedQueue<Customer> queue;
private final ExecutorService executor;
public BankQueueSimulation(int numATMs) {
this.numATMs = numATMs;
this.queue = new ConcurrentLinkedQueue<>();
this.executor = Executors.newFixedThreadPool(numATMs);
}
// 客户类,表示取款人
static class Customer implements Runnable {
private double amount;
public Customer(double amount) {
this.amount = amount;
}
@Override
public void run() {
System.out.println("Customer with " + amount + " arrived at the bank.");
process();
}
private void process() {
// 模拟取钱操作,这里只是一个简单的延迟
try {
Thread.sleep(500); // 假设处理时间
System.out.println("Customer withdrew " + amount + " from the ATM.");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public void startQueue(double[] amounts) {
for (double amount : amounts) {
queue.add(new Customer(amount));
}
while (!queue.isEmpty()) {
executor.execute(queue.poll());
}
executor.shutdown();
}
public static void main(String[] args) {
BankQueueSimulation simulation = new BankQueueSimulation(2); // 假设有2个ATM
double[] customerAmounts = {100, 200, 150, 300}; // 不同金额的客户
simulation.startQueue(customerAmounts);
}
}
```
在这个例子中:
- `BankQueueSimulation` 类初始化了几个ATM(通过`ExecutorService`)和一个并发队列来保存客户。
- `Customer` 类实现了`Runnable`接口,每个实例代表一个客户,包含要取出的金额。
- `startQueue` 方法启动取款过程,根据给定的金额列表创建并添加客户到队列,然后使用线程池执行每个客户的`run`方法。
- 每个客户在`process`方法中模拟取款操作,这里只是简单地睡眠一段时间。
这个模型非常基础,没有处理并发时的资源竞争或优先级调度等问题,但足以说明如何开始构建这样一个模拟。如果你想要进一步复杂化,比如考虑取款机的数量限制、账户余额检查等,那么可以继续扩展这个框架。
阅读全文
相关推荐













