线程安全问题:模拟取钱案例

 

 

 

package Karl.Demo.money;

public class Test {
    public static void main(String[] args) {
        Account acc=new Account(100000);
        new DrawThread(acc,"小明").start();
        new DrawThread(acc,"小红").start();
    }
}
package Karl.Demo.money;

public class DrawThread extends Thread{
    private Account acc;
    public DrawThread(Account acc,String name){
        super(name);
        this.acc=acc;
    }
    @Override
    public void run() {
        //取钱
        acc.drawmoney(100000);
    }
}
package Karl.Demo.money;

public class Account {
    private double money;

    public Account() {
    }

    public Account(double money) {
        this.money = money;
    }

    public double getMoney() {
        return money;
    }

    public void setMoney(double money) {
        this.money = money;
    }

    public void drawmoney(double money) {
        String name=Thread.currentThread().getName();
        if (this.money>=money){
            System.out.println(name + "取钱成功");
            this.money-=money;
            System.out.println(name+"取钱过后,余额为:"+this.money);
        }else {
            System.out.println(name + "取钱失败,余额不足");
        }
    }
}

 

posted @ 2023-06-07 13:53  Karlshell  阅读(10)  评论(0)    收藏  举报