class Account{
private int money;
public Account(int money){
this.money = money;
}
public synchronized int getMoney() {
return money;
}
public synchronized void setMoney(int money) {
this.money = money;
}
public void transfer(Account target,int amount){
if (this.getMoney() >= amount){
this.setMoney(this.getMoney() - amount);
//这里this.getMoney()获得this对象锁完成getMoney()后立刻释放,
// 另一个线程立刻抢到了this对象的锁,进行setMoney(),导致之前getMoney()的值失真
target.setMoney(target.getMoney() + amount);
//同理
}
}
}
记一个Java并发小错误
最新推荐文章于 2024-07-10 21:37:49 发布