多线程下装拆箱的迷惑在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();
  }

 }
}
全部评论

相关推荐

Atica:笑死了我也收到这个,第一时间还以为是婉拒我,然后一看他把卖课名片推过来大彻大悟
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务