java 模拟多人从同一个账户上取钱的过程 假设账户上有10000元钱,3人从上面随机取(范围为100至300)元钱,如果取完了,就提示已经没钱了。
时间: 2024-02-18 10:01:51 浏览: 18
可以使用Java中的线程和同步机制来模拟多人从同一个账户上取钱的过程。以下是示例代码:
```java
public class BankAccount {
private int balance = 10000;
public synchronized void withdraw(int amount, String threadName) {
if (balance >= amount) {
System.out.println(threadName + " withdraws $" + amount + " from the account");
balance -= amount;
System.out.println("Current balance: $" + balance);
} else {
System.out.println(threadName + " tries to withdraw $" + amount + " from the account, but there is not enough money");
}
}
}
public class WithdrawThread implements Runnable {
private BankAccount account;
private String threadName;
public WithdrawThread(BankAccount account, String threadName) {
this.account = account;
this.threadName = threadName;
}
@Override
public void run() {
while (true) {
int amount = (int) (Math.random() * 201 + 100);
account.withdraw(amount, threadName);
try {
Thread.sleep((int) (Math.random() * 1000));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public class Main {
public static void main(String[] args) {
BankAccount account = new BankAccount();
Thread t1 = new Thread(new WithdrawThread(account, "Thread 1"));
Thread t2 = new Thread(new WithdrawThread(account, "Thread 2"));
Thread t3 = new Thread(new WithdrawThread(account, "Thread 3"));
t1.start();
t2.start();
t3.start();
}
}
```
在上面的代码中,BankAccount类代表银行账户,它有一个balance成员变量表示账户余额,还有一个withdraw方法表示从账户上取钱。这个方法是同步方法,使用synchronized关键字来确保在多线程环境下只有一个线程可以执行该方法。
WithdrawThread类代表取钱的线程,它持有一个BankAccount对象和一个线程名字。它的run方法会不断地从账户上取钱,直到账户上没有钱为止。取钱的金额是随机的,范围为100至300。取完钱后,线程会休眠一段随机时间,模拟取钱的时间。
Main类创建了一个BankAccount对象和三个WithdrawThread对象,并将它们都启动。这样就可以模拟多人从同一个账户上取钱的过程了。当账户上没有钱时,取钱的线程会收到提示并停止取钱。