ABA问题代码演示和解决

package JmmVolatile;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.atomic.AtomicStampedReference;

/**
 * 项目名:
 * Created by fu.
 * Created at 2021
 * 描述:
 */
public class ABADemo {
    static AtomicReference atomicReference = new AtomicReference<>(100);
    static AtomicStampedReference atomicStampedReference = new AtomicStampedReference<>(100,1);
public static void main(String[] args) {
    System.out.println("************ABA问题的产生*************");
    new Thread(()->{
        atomicReference.compareAndSet(100,101);
        atomicReference.compareAndSet(101,100);
    },"t1").start();

    new Thread(()->{
       //暂停1秒。保证t1线程已经完成ABA问题
        try {
            TimeUnit.SECONDS.sleep(1);
        }catch (InterruptedException e){
            e.printStackTrace();
        }
        System.out.println(atomicReference.compareAndSet(100,2019)+"\t"+atomicReference.get());
    },"t2").start();

    //暂停一会线程
    try {
        TimeUnit.SECONDS.sleep(2);
    }catch (InterruptedException e){
        e.printStackTrace();
    }
    System.out.println("************ABA问题的解决*************");
    new Thread(()->{
       int atom =atomicStampedReference.getStamp();
        System.out.println(Thread.currentThread().getName()+"\t 第一次的版本号" +atom);
        try {
            TimeUnit.SECONDS.sleep(1);
        }catch (InterruptedException e){
            e.printStackTrace();
        }
        atomicStampedReference.compareAndSet(100,101,atomicStampedReference.getStamp(),atomicStampedReference.getStamp()+1);
        System.out.println(Thread.currentThread().getName()+"\t 第二次的版本号" +atomicStampedReference.getStamp());
        atomicStampedReference.compareAndSet(101,100,atomicStampedReference.getStamp(),atomicStampedReference.getStamp()+1);
        System.out.println(Thread.currentThread().getName()+"\t 第三次的版本号" +atomicStampedReference.getStamp());
    },"t3").start();


    new Thread(()->{
        int atom =atomicStampedReference.getStamp();
        System.out.println(Thread.currentThread().getName()+"\t 第一次的版本号" +atom);
        try {
            TimeUnit.SECONDS.sleep(3);
        }catch (InterruptedException e){
            e.printStackTrace();
        }
        boolean result = atomicStampedReference.compareAndSet(100,2020,atom,atom+1);
        System.out.println(Thread.currentThread().getName()+"\t 修改是否成功" +result+atomicStampedReference.getStamp());

        System.out.println(Thread.currentThread().getName()+"\t 当前最新值" +atomicStampedReference.getReference());
    },"t4").start();
}
}

你可能感兴趣的:(代码,java)