A和B互相转账,用Java代码
时间: 2024-02-23 19:56:21 浏览: 30
假设A和B各有一个银行账户,我们可以使用Java的多线程机制来实现互相转账的功能。具体实现如下:
```java
public class BankTransfer {
private static final int NACCOUNTS = 2; // 账户数量
private static final double INITIAL_BALANCE = 1000; // 初始余额
public static void main(String[] args) {
Bank bank = new Bank(NACCOUNTS, INITIAL_BALANCE); // 创建银行
// 创建多个线程,模拟A和B的转账行为
for (int i = 0; i < NACCOUNTS; i++) {
int fromAccount = i;
int toAccount = (i + 1) % NACCOUNTS;
double amount = 100; // 转账金额
new Thread(() -> {
try {
bank.transfer(fromAccount, toAccount, amount); // 执行转账操作
} catch (InterruptedException e) {
e.printStackTrace();
}
}).start();
}
}
}
class Bank {
private final double[] accounts;
public Bank(int n, double initialBalance) {
accounts = new double[n];
Arrays.fill(accounts, initialBalance);
}
// 转账操作
public synchronized void transfer(int from, int to, double amount) throws InterruptedException {
while (accounts[from] < amount) {
wait(); // 等待余额充足
}
System.out.print(Thread.currentThread());
accounts[from] -= amount;
System.out.printf(" %10.2f from %d to %d", amount, from, to);
accounts[to] += amount;
System.out.printf(" Total Balance: %10.2f%n", getTotalBalance());
notifyAll(); // 唤醒等待的线程
}
// 获取总余额
public synchronized double getTotalBalance() {
double sum = 0;
for (double a : accounts)
sum += a;
return sum;
}
// 获取账户数量
public int size() {
return accounts.length;
}
}
```
在上面的代码中,我们创建了一个Bank类表示银行,该类包含多个账户,每个账户有一个初始余额。Bank类提供了转账方法transfer()和获取总余额方法getTotalBalance()。
在main()方法中,我们创建了两个账户A和B,然后创建多个线程模拟A和B的转账行为。每个线程执行transfer()方法进行转账,如果账户余额不足,则线程会进入等待状态;转账完成后,线程会唤醒其它等待的线程。最后,我们打印出每次转账后银行的总余额。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)