package d3_thread_safe;
public class Account {
private String cardId;
private double money;//账户余额
public Account() {
}
public Account(String cardId, double money) {
this.cardId = cardId;
this.money = money;
}
public void drawMoney(double money) {
//判断是谁来取钱
String name = Thread.currentThread().getName();
//判断余额是否足够
if (this.money >= money) {
//取钱
System.out.println(name + "来取钱成功,吐出:" + money);
//更新余额
this.money -= money;
System.out.println("剩余:" + this.money);
} else {
System.out.println("余额不足");
}
}
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;
}
}
package d3_thread_safe;
/*
取钱的线程类
*/
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 d3_thread_safe;
/*
需求:模拟取钱案例
解决线程安全问题的办法就是加锁
*/
public class ThreadDemo {
public static void main(String[] args) throws Exception {
//1、定义一个线程类,创建一个共享账户对象
Account acc = new Account("ICBC-111", 100000);
//2、创建两个线程对象 代表小明和小红同时进来
new DrawThread(acc, "小明").start();
Thread.sleep(3000); //这里可以采取休眠来解决安全嘛?
new DrawThread(acc, "小红").start();
}
}
提出的问题在最后代码块注释中 Thread.sleep(3000)哪一行里