20、原子引用:AtomicReference
原子类 AtomicInteger 的ABA问题谈谈?原子更新引用知道吗?
CAS 会导致 ABA的问题!
CAS算法的前提是:取出内存中某个时刻的数据,比较并交换! 在这个时间差内有可能数据被修改!
如下示例:
package com.interview.concurrent.cas;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
/**
* @author yangxj
* @description 描述:CAS带来的ABA问题
* @date 2020/2/25 17:10
*/
public class CasAbaQuestionDemo {
public static void main(String[] args) throws InterruptedException {
AtomicInteger atomicInteger = new AtomicInteger(5);
/**
* @description:A线程已经将5修改为其他数
* @author yangxj
* @date 2020/2/25 17:23
*/
new Thread(() -> {
atomicInteger.compareAndSet(5,200);
},"A").start();
/**
* @description:C线程是小偷,偷偷的改动数据,然后又改回原来的5
* @author yangxj
* @date 2020/2/25 17:23
*/
new Thread(() -> {
atomicInteger.compareAndSet(200,210);
atomicInteger.compareAndSet(210,5);
},