java
package Thread_api_test;
public class ThreadSafety {
//模拟线程安全问题
public static void main(String[] args) {
//1:创建一个账户对象 代表两个人的共享账户
Account acc=new Account("ICBC",10000);
//创建两个线程 分别两个人 再去同一个账户里取钱10000
new DrawThread(acc,"第一个人").start(); //第1个人
new DrawThread(acc,"第二个人").start(); //第2个人
}
}
java
package Thread_api_test;
public class DrawThread extends Thread {
private Account acc;
public DrawThread(Account acc,String name){
super(name);
this.acc=acc;
}
@Override
public void run() {
super.run();
//取钱
acc.drawMoney(10000);
}
}
java
package Thread_api_test;
public class Account {
private String carId; //卡号
private double money ;//余额
public Account() {
}
public Account(String carId, double money) {
this.carId = carId;
this.money = money;
}
public void drawMoney(double mony) {
//先知道那个人来取钱
String name= Thread.currentThread().getName();
if (this.money>=mony){
System.out.println(name+"来取钱"+mony+"成功!");
this.money-=mony;
System.out.println(name+"来取钱后:剩余的":"+this.money);
}else{
System.out.println(name+"来取钱:余额不足~~!");
}
}
public String getCarId() {
return carId;
}
public void setCarId(String carId) {
this.carId = carId;
}
public double getMoney() {
return money;
}
public void setMoney(double money) {
this.money = money;
}
}