class Bank {
private AtomicReference<Double> balance=new AtomicReference<>(0.0); // 账户余额
private AtomicInteger integer=new AtomicInteger();
/**
* 存款
*
* @param money 存入金额
*/
public synchronized void deposit(double money) {
//如果改成把old的类型改成double就会死循环,是什么原理
Double old = balance.get();
while (!balance.compareAndSet(old, old+money)) {
old = balance.get();
}
}
public synchronized void deposit1(int money) {
//todo
int old = integer.get();
while (!integer.compareAndSet(old, old+money)) {
old = integer.get();
}
}
/**
* 获得账户余额
*/
public double getBalance() {
return balance.get();
}
public double getBal() {
return integer.get();
}
public static void main(String[] args) throws InterruptedException {
Bank account = new Bank();
//todo:100线程并发
for(int i=0;i<1000;i++){
Runnable runnable = () ->{
account.deposit1(1);
account.deposit(1);
};
new Thread(runnable).start();
}
}
}
作者:用心的卷王求你们别卷了
链接:多线程下装拆箱的迷惑在deposit方法_牛客网
来源:牛客网
求助:多线程下装拆箱的迷惑,问题在deposit方法
最新推荐文章于 2024-11-03 11:01:20 发布