多线程下装拆箱的迷惑在deposit方法
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();
}
}
}
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();
}
}
}
全部评论
相关推荐
09-29 15:24
香港中文大学 运营 点赞 评论 收藏
分享