gpt4 book ai didi

java - 如何在简单的现金存取程序中处理多线程

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:43:17 25 4
gpt4 key购买 nike

<分区>

我的导师说要使用多线程来更新帐户管理系统。下面给出了该系统的粗略概念。 enter image description here

这是我的源代码。

账户类别

public class Account {
int balance= 1000;

public int getBal(){
return balance;
}

public void withdraw(int bal){
balance= balance-bal;
}

public void deposit(int bal){
balance= balance+bal;
}
}

ThreadExercise 类

public class ThreadExercise implements Runnable{

Account acc = new Account();

public static void main(String[] args) {
ThreadExercise ts = new ThreadExercise();
Thread t1 = new Thread(ts, "person 1");
Thread t2 = new Thread(ts, "person 2");
Thread t3 = new Thread(ts, "person 3");
t1.start();
t2.start();
t3.start();
}

@Override
public void run() {
for (int i = 0; i < 3; i++) {
makeWithdraw(100);
if (acc.getBal() < 0) {
System.out.println("account is overdrawn!");
}
deposit(200);
}
}


private synchronized void makeWithdraw(int bal){
if (acc.getBal()>=bal) {
System.out.println(Thread.currentThread().getName()+" "+ "is try to withdraw");
try {
Thread.sleep(100);
} catch (Exception e) {
e.printStackTrace();
}
acc.withdraw(bal);
System.out.println(Thread.currentThread().getName()+" "+ "is complete the withdraw");
}else{
System.out.println(Thread.currentThread().getName()+ " "+"doesn't have enough money for withdraw ");
}
}

private synchronized void deposit(int bal){
if (bal>0) {
System.out.println(Thread.currentThread().getName()+" "+ " is try to deposit");
try {
Thread.sleep(100);
} catch (Exception e) {
e.printStackTrace();
}
acc.deposit(bal);
System.out.println(Thread.currentThread().getName()+" "+ "is complete the deposit");
}else{
System.out.println(Thread.currentThread().getName()+ " "+"doesn't have enough money for deposit");
}
}
}

代码运行良好。但我真的认为有些东西缺少这段代码。你能帮我找出那个错误吗?


同步 ThreadExercise 类中的 makeWithdraw() 和 deposit() 方法是否不够,我是否应该删除同步并同步 Account 类中的 withdraw() 和 deposit()。请给我一个清晰的思路。
感谢您的支持。

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com