并发编程-使用AtomicStampedReference解决CAS ABA问题
package cn.bikan8;


import java.util.concurrent.atomic.AtomicStampedReference;

/**
 * @Author 小浩
 * @Date 2020/6/9 10:47
 * @Version 1.0
 * 模拟用AtomicStampedReference 解决CAS ABA问题
 **/
public class Task {
    private static AtomicStampedReference<Integer> atomicStampedReference = new AtomicStampedReference<>(0, 0);

    public static void main(String[] args) throws Exception{

        Thread thread1 = new Thread() {
            @Override
            public void run() {
                int stamp = atomicStampedReference.getStamp();
                Integer reference = atomicStampedReference.getReference();
                Boolean result = atomicStampedReference.compareAndSet(reference, reference + 1, stamp, stamp + 1);
                System.out.println("当前值" + stamp + " 当前版本" + stamp +" CAS结果"+result);
            }
        };

//      故意给一个错误的版本号,
        Thread thread2 = new Thread() {
            @Override
            public void run() {
                int stamp = atomicStampedReference.getStamp();
                Integer reference = atomicStampedReference.getReference();
                Boolean result = atomicStampedReference.compareAndSet(reference, reference + 1, 0, stamp + 1);
                System.out.println("当前值" + stamp + " 当前版本" + stamp +" CAS结果"+result);
            }
        };

        thread1.start();
        thread1.join();
        thread2.start();
        thread2.join();

    }

}

加一个自增的版本号就可以解决这个问题

© 版权声明
THE END
喜欢就支持以下吧
点赞0
分享
评论 抢沙发