AtomicStampedReference

package japan.example.test;

import java.io.IOException;
import java.util.concurrent.atomic.AtomicStampedReference;

public class FinalTest {

    public final static AtomicStampedReference<String> ATOMIC_REFERENCE = new AtomicStampedReference<String>("abc", 0);

    public static void main(String[] args) throws IOException {
        for (int i = 0; i < 100; i++) {
            final int num = i;
            final int stamp = ATOMIC_REFERENCE.getStamp();
            new Thread(() -> {
                try {
                    Thread.sleep(Math.abs((int) (Math.random() * 100)));
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                if (ATOMIC_REFERENCE.compareAndSet("abc", "abc2", stamp, stamp + 1)) {
                    System.out.println("我是线程:" + num + ",我获得了锁进行了对象修改!");
                }
            }).start();
        }

        new Thread(() -> {
            int stamp = ATOMIC_REFERENCE.getStamp();
            while (ATOMIC_REFERENCE.compareAndSet("abc2", "abc", stamp, stamp + 1)) {
                System.out.println("已经改回为原始值!");
            }
        }).start();

        // System.in.read();
    }

}
原文地址:https://www.cnblogs.com/jpit/p/8288299.html