Java中的并发问题案例(二)---多人同时通过一张银行卡取款

Java中的并发问题案例(二)—多人同时通过一张银行卡取款

01 代码

public class SynTest1 {
    public static void main(String[] args) {
        Account account = new Account(10000, 12345678);

         new Bank("A", account, 4000).start();
         new Bank("B", account, 7000).start();
         new Bank("C", account, 4000).start();

    }
}
class Account {
    int deposit;//存款
    int number;//银行卡号

    public Account(int deposit,int number){
        this.deposit=deposit;
        this.number=number;
    }
}
class Bank extends Thread{
    //存钱
    //取钱
    Account account;
    int withdraw;//取钱
    int balance;//余额

    public Bank(String name,Account account,int withdraw){
        super(name);//用父类构造
        this.account=account;
        this.withdraw=withdraw;
    }

    @Override
    public void run() {
        draw();
    }

    private void draw() {
        //同步监视块:哪个对象要进行增删改查的操作就锁哪个对象
        synchronized (account){
            //判断能否取钱,账户存款小于0立即返回
            if (account.deposit<=0){
                System.out.println(Thread.currentThread().getName()+"取钱失败,余额为"+account.deposit);
                return;
            }
            //为了放大问题发生性,加入延时

            //判断余额是否充足
            if (account.deposit-withdraw<=0){
                System.out.println(Thread.currentThread().getName()+"取钱失败,余额为"+account.deposit);
                return;
            }
            //通过延时放大问题发生性
        try {
            Thread.currentThread().sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

            balance=account.deposit-withdraw;//余额=存款-取款
            account.deposit=balance;//当前存款=余额
            System.out.println(Thread.currentThread().getName()+"成功取出"+withdraw+"人民币");
            System.out.println("账户"+account.number+"余额为:"+balance);
        }
    }
}

02 运行结果

在这里插入图片描述

  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值