作用

通过版本号解决ABA的问题。

示例

public class AtomicStampedReferenceDemo {
    static AtomicStampedReference<Integer> stampedReference = new AtomicStampedReference<>(1, 1);

    public static void main(String[] args) throws InterruptedException {
        int oldStamp = stampedReference.getStamp();
        Thread thread1 = new Thread(new Runnable() {
            @Override
            public void run() {
                boolean result = stampedReference.compareAndSet(1, 2, oldStamp, oldStamp + 1);
                System.out.println("当前值:1,预设2,当前版本号:" + stampedReference.getStamp() + ",结果:" + result);
            }
        });
        Thread thread2 = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                boolean result = stampedReference.compareAndSet(2, 3, oldStamp, oldStamp + 1);
                System.out.println("当前值:2,预设3,当前版本号:" + stampedReference.getStamp() + ",结果:" + result);
            }
        });
        thread1.start();
        thread2.start();
        Thread.sleep(2000);
        System.out.println("当前值:" + stampedReference.getReference() + ",当前版本号:" + stampedReference.getStamp());
    }
}

运行结果如下:
clipboard.png
这里用休眠,让线程1和线程2一次执行,通过结果可以看出来,线程1执行成功,而线程2执行失败。原因就是因为版本号对不上。


大军
847 声望183 粉丝

学而不思则罔,思而不学则殆