CAS有3个操作数。内存值V,旧的预约值A,要修改后的新值B。当且仅当预期值A和预期值V相同时,将内存值V修改为新值B。当且仅当预期值A和内存值V相同时,将内存值V修改为B,否则什么都不做。

应用1.Atomic包

eg.AtomicInteger

它的增加和减少操作都是原子性的,不会出现多线程下的数据不一致问题。

++i操作:

public final int incrementAndGet(){
  for(;;){
    int current =get();
    int next =current +1;
    if(compareAndSet(current, next))//采用了CAS
      return next;  
  }  
}

 

相关文章:

  • 2022-12-23
  • 2021-04-25
  • 2021-05-17
  • 2021-09-02
  • 2021-05-10
  • 2022-03-10
  • 2021-07-01
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2021-10-10
  • 2022-12-23
  • 2021-07-27
  • 2022-12-23
  • 2021-09-11
相关资源
相似解决方案