码迷,mamicode.com
首页 > 其他好文 > 详细

AtomicStampedReference

时间:2020-06-18 11:14:07      阅读:72      评论:0      收藏:0      [点我收藏+]

标签:and   throws   OLE   ref   java   integer   tom   span   rgs   

使用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

 

AtomicStampedReference

标签:and   throws   OLE   ref   java   integer   tom   span   rgs   

原文地址:https://www.cnblogs.com/zheaven/p/13156078.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!