关于#java#的问题:账户的初始余额是20000元,两个线程每次存储1000 元,分别各存储20000元
模拟一个简单的银行系统,使用两个不同的线程向同一个账户存钱。账户的初始余额是20000元,两个线程每次存储1000 元,分别各存储20000元,不允许出现错误数据。
public class BankSystem {
public static void main(String[] args) {
Account account = new Account(20000);
Thread thread1 = new Thread(new DepositThread(account, 1000));
Thread thread2 = new Thread(new DepositThread(account, 1000));
thread1.start();
thread2.start();
try {
thread1.join();
thread2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("最终账户余额:" + account.getBalance());
}
}
class Account {
private int balance;
public Account(int balance) {
this.balance = balance;
}
public synchronized void deposit(int amount) {
balance += amount;
}
public int getBalance() {
return balance;
}
}
class DepositThread implements Runnable {
private Account account;
private int amount;
public DepositThread(Account account, int amount) {
this.account = account;
this.amount = amount;
}
@Override
public void run() {
for (int i = 0; i < 20; i++) {
synchronized (account) {
account.deposit(amount);
}
}
}
}
在上述代码中,我们定义了一个
Account
类表示银行账户,其中包含了存款方法
deposit()
和获取余额方法
getBalance()
。
deposit()
方法使用
synchronized
关键字来确保在多线程环境下对账户余额的操作是线程安全的。 然后,我们定义了一个
DepositThread
类实现
Runnable
接口,表示存款线程。每个存款线程在
run()
方法中循环执行20次存款操作,每次存款1000元。 在
BankSystem
类中,我们创建了一个初始余额为20000元的账户对象,并创建两个存款线程。然后,我们启动这两个线程并等待它们执行完毕。最后,打印出最终的账户余额。 我们在
deposit()
方法上使用了
synchronized
关键字来确保对账户余额的并发访问是线程安全的。此外,我们还在
run()
方法中使用
synchronized
块来同步对账户的存款操作。