java并发编程学习之casAtomicStampedReference三

45次阅读

共计 970 个字符,预计需要花费 3 分钟才能阅读完成。

作用

通过版本号解决 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());
    }
}

运行结果如下:

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

正文完
 0