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