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

 }
}
全部评论

相关推荐

jnsytgsyqj...:简历跟测试没关系,你更适合运营
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
07-21 13:38
8月实习会变多吗现在还没找到实习该怎么办...回复的hr好少
码农索隆:3-4月就要开始找,基本上6月份就发offer,7月初已经开始暑期实习了。
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务