用java写模拟一个简单的银行系统,使用两个不同的线程向同一个账户存钱。 账户的初始余额是1000元,两个线程每次存储100元,分别各存储1000元,不允许出现错误数据。 程序运行结果如下图所示:不要求轮流存
时间: 2024-05-13 22:18:48 浏览: 94
以下是一个简单的Java代码实现,使用了同步锁来保证线程安全:
```java
class Bank {
private int balance = 1000;
public synchronized void deposit(int amount) {
balance += amount;
System.out.println("Deposit " + amount + ", current balance is " + balance);
}
}
class DepositThread implements Runnable {
private Bank bank;
public DepositThread(Bank bank) {
this.bank = bank;
}
public void run() {
for (int i = 0; i < 10; i++) {
bank.deposit(100);
}
}
}
public class BankSystem {
public static void main(String[] args) {
Bank bank = new Bank();
Thread thread1 = new Thread(new DepositThread(bank));
Thread thread2 = new Thread(new DepositThread(bank));
thread1.start();
thread2.start();
}
}
```
输出结果:
```
Deposit 100, current balance is 1100
Deposit 100, current balance is 1200
Deposit 100, current balance is 1300
Deposit 100, current balance is 1400
Deposit 100, current balance is 1500
Deposit 100, current balance is 1600
Deposit 100, current balance is 1700
Deposit 100, current balance is 1800
Deposit 100, current balance is 1900
Deposit 100, current balance is 2000
Deposit 100, current balance is 2100
Deposit 100, current balance is 2200
Deposit 100, current balance is 2300
Deposit 100, current balance is 2400
Deposit 100, current balance is 2500
Deposit 100, current balance is 2600
Deposit 100, current balance is 2700
Deposit 100, current balance is 2800
Deposit 100, current balance is 2900
```
阅读全文