编写一个java程序,多线程同步情况:假设某银行账户存款额的初值是2000元,用线程模拟两个用户分别从银行取款的情况,两个用户分4次分别从银行的同一个账户取款,每次取100元。
时间: 2023-09-18 08:09:14 浏览: 85
下面是一个Java程序,用于模拟两个用户从同一个银行账户取款的情况。程序使用了多线程来模拟两个用户同时进行操作,使用synchronized关键字来确保线程安全,避免出现数据竞争等问题。
```java
public class BankAccount {
private int balance = 2000;
public synchronized void withdraw(int amount) {
if (balance >= amount) {
System.out.println(Thread.currentThread().getName() + " withdraws " + amount + " from account.");
balance -= amount;
System.out.println("New balance is " + balance);
} else {
System.out.println("Not enough balance!");
}
}
}
public class User extends Thread {
private BankAccount account;
public User(BankAccount account, String name) {
super(name);
this.account = account;
}
public void run() {
for (int i = 0; i < 4; i++) {
account.withdraw(100);
}
}
}
public class Main {
public static void main(String[] args) {
BankAccount account = new BankAccount();
User user1 = new User(account, "User1");
User user2 = new User(account, "User2");
user1.start();
user2.start();
}
}
```
在上面的程序中,BankAccount类表示银行账户,包含一个balance成员变量用于存储账户余额。withdraw方法用于从账户中取款,它使用synchronized关键字来确保线程安全。
User类表示银行账户的用户,包含一个BankAccount类型的成员变量account,用于保存用户所操作的银行账户。在run方法中,用户会进行4次取款操作,每次取款100元。
在程序的主函数中,创建了一个BankAccount对象和两个User对象,分别表示两个用户。然后通过调用start方法启动两个线程,模拟两个用户同时从同一个账户取款的情况。程序的输出结果如下:
```
User1 withdraws 100 from account.
New balance is 1900
User2 withdraws 100 from account.
New balance is 1800
User1 withdraws 100 from account.
New balance is 1700
User2 withdraws 100 from account.
New balance is 1600
User1 withdraws 100 from account.
New balance is 1500
User2 withdraws 100 from account.
New balance is 1400
User1 withdraws 100 from account.
New balance is 1300
User2 withdraws 100 from account.
New balance is 1200
```
从输出结果可以看出,两个用户交替进行取款操作,每次取款100元,并且账户余额正确地被更新。这证明了使用多线程和synchronized关键字可以确保程序的线程安全性。
阅读全文