20220522_线程安全问题示例_同时取钱

账户类
取钱方法在账户里,属于账户对象

public class Account {
    private String accID;
    private double balance;

    public Account() {
    }

    public Account(String accID, double balance) {
        this.accID = accID;
        this.balance = balance;
    }

    public String getAccID() {
        return accID;
    }

    public void setAccID(String accID) {
        this.accID = accID;
    }

    public double getBalance() {
        return balance;
    }

    public void setBalance(double balance) {
        this.balance = balance;
    }

    public void withdraw(double money){
        String name = Thread.currentThread().getName();
        if (this.balance >= money){
            System.out.println(name+ " withdraw succeed, amount is:"+money);
            this.balance -= money;
            System.out.println("After "+name+"'s withdraw, the balance changed to: "+ balance);
        }else {
            System.out.println("Sorry, your amount is over your balance.");
        }
    }
}

取钱线程类
创建线程,把线程的run方法重写,里头调用账户的取钱方法

public class withdrawThread extends Thread {
    private Account acc;

    public withdrawThread(Account acc,String name) {
        super(name);
        this.acc = acc;
    }

    @Override
    public void run() {
        acc.withdraw(100000.0);
    }
}

执行体
这个账户的构造器里写一个账户ID的成员变量就意思意思,不影响本例

public class ThreadSecurityDemo1 {
    public static void main(String[] args) {
        Account acc = new Account("MTU_010203",100000);

        new withdrawThread(acc,"Peter").start();
        new withdrawThread(acc,"Diana").start();
        
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值