java多线程银行存取钱
时间: 2023-07-05 13:35:32 浏览: 52
Java多线程实现银行存款与取款线程
4星 · 用户满意度95%
好的,这是一个经典的多线程问题。下面是一个简单的示例代码:
```java
public class BankAccount {
private int balance;
public BankAccount(int balance) {
this.balance = balance;
}
public synchronized void deposit(int amount) {
balance += amount;
}
public synchronized void withdraw(int amount) {
balance -= amount;
}
public synchronized int getBalance() {
return balance;
}
}
public class BankTransaction implements Runnable {
private BankAccount account;
private boolean deposit;
private int amount;
public BankTransaction(BankAccount account, boolean deposit, int amount) {
this.account = account;
this.deposit = deposit;
this.amount = amount;
}
@Override
public void run() {
if (deposit) {
account.deposit(amount);
} else {
account.withdraw(amount);
}
}
}
public class Main {
public static void main(String[] args) {
BankAccount account = new BankAccount(1000);
Thread t1 = new Thread(new BankTransaction(account, true, 500));
Thread t2 = new Thread(new BankTransaction(account, false, 300));
t1.start();
t2.start();
try {
t1.join();
t2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Final balance: " + account.getBalance());
}
}
```
这个示例代码中,BankAccount 类表示银行账户,有三个方法:deposit、withdraw 和 getBalance,分别用于存款、取款和查询余额。这三个方法都使用 synchronized 关键字来实现线程安全。
BankTransaction 类表示银行交易,有三个属性:BankAccount 对象、交易类型(存款或取款)和金额。它的 run 方法根据交易类型调用 BankAccount 对象的 deposit 或 withdraw 方法。
Main 类启动两个线程,分别执行存款和取款操作。最后输出账户的余额。注意使用 join 方法等待两个线程执行完毕后再输出余额,以确保输出的余额是正确的。
阅读全文