多线程模拟银行取款业务

多线程模拟银行取款业务

public class Account {
    int id; //编号
    double balance;//余额

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

    public Account() {
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public double getBalance() {
        return balance;
    }

    public void setBalance(double balance) {
        this.balance = balance;
    }
    public void getMoney(double money){
        synchronized ("1") {
            if (money > this.getBalance()) { //对输入金额进行判断
                System.out.println(Thread.currentThread().getName()+"您的取款金额为" + money + "\t" + "您的余额为" + this.getBalance() + "\t" + "取款失败");
                return;
            } else {
                double begin = this.getBalance();//取款之前的余额
                double end = begin - money;//取款之后的余额
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                this.setBalance(end);//更新余额
                System.out.println(Thread.currentThread().getName()+"取款成功,余额为"+this.getBalance());
            }
        }
    }
}
public class AccountThread extends Thread {
    Account account=new Account();
    public AccountThread(Account account){
        this.account=account;
    }

    @Override
    public void run() {
        double money=17777;
        account.getMoney(money);

    }
}
public class AccountThreadText {
    public static void main(String[] args) {
        Account account=new Account(1,20000);
        AccountThread t1=new AccountThread(account);
        AccountThread t2=new AccountThread(account);
        t1.setName("客户1\t");
        t2.setName("客户2\t");
        t1.start();
        t2.start();
    }
}
//取款金额超过余额
客户1	取款成功,余额为2223.0
客户2	您的取款金额为17777.0	您的余额为2223.0	取款失败

//取款金额小于等于余额
客户1	取款成功,余额为10000.0
客户2	取款成功,余额为0.0

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值