什么是线程安全问题
用程序模拟线程安全问题
主线程
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;}@Overridepublic 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;}}