首页 新闻 会员 周边 捐助

这段代码出现线程不安全的情况,为什么会出现,怎么改

0
悬赏园豆:10 [已关闭问题] 关闭于 2021-05-28 16:52

public class Bank {
public static void main(String[] args) {
Account account = new Account(100);

    new Thread(new card(account, 50), "小明").start();
    new Thread(new card(account, 100), "小红").start();
}

}

class Account {
int balance;

public Account(int balance) {
    this.balance = balance;
}

public synchronized void takeMoney(int takeMoney,int handMoney) {

    if (this.balance <= 0) {
        System.out.println("余额不足-------");
        return;
    }

    this.balance = this.balance - takeMoney;
    handMoney = handMoney + takeMoney;
    System.out.println(Thread.currentThread().getName() + "手上的" + handMoney);
    System.out.println("账户余额" + this.balance);
}

}

class card implements Runnable {

private Account account;

private int takeMoney;

private int handMoney=0;


public card(Account account, int takeMoney) {
    this.account = account;
    this.takeMoney = takeMoney;

}

@Override
public void run() {
    account.takeMoney(takeMoney,handMoney);

}

}

小埋的哥哥!的主页 小埋的哥哥! | 初学一级 | 园豆:110
提问于:2021-05-28 16:40
< >
分享
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册