可见性问题,可以通过volatile解决
原子性问题,可以采用互斥锁方案

2.无锁方案


public class Test {
  AtomicLong count = 
    new AtomicLong(0);
  void add10K() {
    int idx = 0;
    while(idx++ < 10000) {
      count.getAndIncrement();
    }
  }
}

count 由long类型变为AtomicLong
无锁方案最大好处就是性能,互斥锁为了保证互斥性,加锁,解锁操作,消耗性能.
拿不到锁的线程还会进入阻塞状态,触发线程切换.
无锁方案没有性能消耗,还能保证互斥性

3.无锁方案的实现原理

cpu指令CAS
硬件支持而已
CAS指令包含3个参数:共享变量的内存地址A,用于比较的值B和共享变量的新值C
并且当内存中的地址A处的值等于B时候,才能将内存中的A出的值更新为新值C


class SimulatedCAS{
  int count;
  synchronized int cas(
    int expect, int newValue){
    // 读目前count的值
    int curValue = count;
    // 比较目前count值是否==期望值
    if(curValue == expect){
      // 如果是,则更新count的值
      count = newValue;
    }
    // 返回写入前的值
    return curValue;
  }
}

只有当内存中count的值等于期望值A时,才能将内存中的count值更新为计算结果A+1

相关文章:

  • 2022-12-23
  • 2021-11-12
  • 2021-10-13
  • 2022-02-21
  • 2021-12-19
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2020-02-27
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2020-03-19
相关资源
相似解决方案