Java线程安全问题

什么是线程安全问题

Java线程安全问题_第1张图片

 Java线程安全问题_第2张图片

 

 用程序模拟线程安全问题

Java线程安全问题_第3张图片

 主线程

package com.itheima.d3;

public class ThreadTest {
    public static void main(String[] args) {
        //1、创建一个账户对象,代表两个人的共享账户
        Accout acc = new Accout("ICBC-110",100000);
        //2、创建两个线程,分别代表小明、小红,再去同一个账户对象中去取钱10万
        new DrawThread(acc,"小明").start();//小明
        new DrawThread(acc,"小红").start();//小红
    }
}

子线程

package com.itheima.d3;

public class DrawThread extends Thread{
    private Accout acc;
    public DrawThread(Accout acc, String name){
        super(name);
        this.acc = acc;
    }

    @Override
    public void run() {
        //取钱(小明、小红)
        acc.drawMoney(100000);
    }
}

方法类

package com.itheima.d3;

public class Accout {
    private String cardId;
    private double money;

    public Accout() {
    }

    public Accout(String cardId, double money) {
        this.cardId = cardId;
        this.money = money;
    }

    public void drawMoney(double money) {
        //是谁来取钱
        String name = Thread.currentThread().getName();
        //1、判断余额是否足够
        if (this.money >= money){
            System.out.println(name + "来取钱" + money + "成功");
            this.money -= money;
            System.out.println(name + "取钱后余额" + this.money);
        }else {
            System.out.println(name + "来取钱余额不足");
        }
    }

    public String getCardId() {
        return cardId;
    }

    public void setCardId(String cardId) {
        this.cardId = cardId;
    }

    public double getMoney() {
        return money;
    }

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

}

你可能感兴趣的:(Java多线程,java,Java的题目案例,java,开发语言)