Java零基础学java之多线程--16线程不安全案例02

package com.li.thread_synchronized;

//不安全取钱
public class UnsafeWithdrawMoney {
    public static void main(String[] args) {
        //账户
        Account account = new Account("结婚基金",100);
        //取钱
        WithdrawMoney me = new WithdrawMoney(account,50);
        WithdrawMoney wife = new WithdrawMoney(account,100);
        new Thread(me,"我").start();
        new Thread(wife,"妻子").start();
    }
}
//账户
class Account {
    String name;//账户名
    int money;//卡余额

    public Account(String name, int money) {
        this.name = name;
        this.money = money;
    }
}

//模拟银行取款
class WithdrawMoney implements Runnable{

    Account account;//账户
    int withdrawMoney;//取的钱

    public WithdrawMoney(Account account, int withdrawMoney) {
        this.account = account;
        this.withdrawMoney = withdrawMoney;
    }

    //取钱
    @Override
    public void run() {
        //判断账户有没有钱
        if (account.money-withdrawMoney<0) {
            System.out.println(Thread.currentThread().getName() + ",账户余额不足,取不了,余额为:" + account.money);
            return;
        }
        //模拟延时
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        //卡余额 = 余额 - 取的钱
        account.money = account.money - withdrawMoney;
        System.out.println(account.name + "余额:" + account.money);
        System.out.println(Thread.currentThread().getName()+ "取了:" + withdrawMoney);


    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值