• AtomicStampedReference


    使用AtomicStampedReference解决CAS机制中ABA问题

    package concurrency;
    
    import java.util.concurrent.TimeUnit;
    import java.util.concurrent.atomic.AtomicStampedReference;
    
    public class AtomicStampedReferenceTest {
        private static AtomicStampedReference<Integer> atomicref = new AtomicStampedReference<Integer>(100, 0);
        
        public static void main(String[] args) throws InterruptedException {
            Thread t1 = new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        TimeUnit.SECONDS.sleep(1);
                        boolean success = atomicref.compareAndSet(100, 101, atomicref.getStamp(), atomicref.getStamp() + 1);
                        System.out.println("t1:=" + success);
                        success = atomicref.compareAndSet(101, 100, atomicref.getStamp(), atomicref.getStamp() + 1);
                        System.out.println("t1:=" + success);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            });
            
            Thread t2 = new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        int stamp = atomicref.getStamp();
                        System.out.println("Before sleep:stamp=" + stamp);
                        TimeUnit.SECONDS.sleep(2);
                        boolean success = atomicref.compareAndSet(100, 101, stamp, stamp + 1);
                        System.out.println("t2:=" + success);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            });
            
            t1.start();
            t2.start();
            t1.join();
            t2.join();
        }
    }

    测试结果:

    Before sleep:stamp=0
    t1:=true
    t1:=true
    t2:=false
  • 相关阅读:
    Linux -- touch
    Linux -- ls
    Linux -- 手动新建用户
    Linux -- id
    Linux -- chfn
    Linux -- finger
    Linux -- newgrp
    浅谈java中线程和操作系统线程
    java虚拟机入门(五)- 常见垃圾回收器及jvm实现
    java虚拟机入门(四)-垃圾回收的故事
  • 原文地址:https://www.cnblogs.com/zheaven/p/13156078.html
Copyright © 2020-2023  润新知