classUser{private String name;privateint age;publicUser(String name,int age){this.name = name;this.age = age;}@Overridepublic String toString(){return"User{"+"name='"+ name +'\''+", age="+ age +'}';}}publicclassTestAtomicRef{publicstaticvoidmain(String[] args){
User z3 =newUser("z3",15);
User l4 =newUser("l4",25);
AtomicReference<User> ref =newAtomicReference<>();
ref.set(z3);
System.out.println(ref.compareAndSet(z3, l4)+" "+ref.get());}}
AtomicStampedReference结局ABA 问题
publicclassTestAtomicStampedReference{static AtomicReference<Integer> ref =newAtomicReference<>(1);static AtomicStampedReference<Integer> sref =newAtomicStampedReference(1,1);publicstaticvoidmain(String[] args){
System.out.println(" =========== ABA 问题 ===========");newThread(()->{
System.out.println(ref.compareAndSet(1,127));//注意 Integer 类型 127 以上 地址不同 具体百度 /**
* Returns an {@code Integer} instance representing the specified
* {@code int} value. If a new {@code Integer} instance is not
* required, this method should generally be used in preference to
* the constructor {@link #Integer(int)}, as this method is likely
* to yield significantly better space and time performance by
* caching frequently requested values.
*
* This method will always cache values in the range -128 to 127,
* inclusive, and may cache other values outside of this range.
*
* @param i an {@code int} value.
* @return an {@code Integer} instance representing {@code i}.
* @since 1.5
*//* public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}*/
System.out.println(ref.compareAndSet(127,1));},"A").start();newThread(()->{try{ TimeUnit.SECONDS.sleep(1);}catch(InterruptedException e){}
System.out.println(Thread.currentThread().getName()+" 结果:"+ ref.compareAndSet(1,2022)+"值: "+ ref.get());},"B").start();try{ TimeUnit.SECONDS.sleep(3);}catch(InterruptedException e){}
System.out.println(" =========== ABA 问题 解决 ===========");newThread(()->{
System.out.println(Thread.currentThread().getName()+" 初始版本 =》 "+ sref.getStamp());try{ TimeUnit.SECONDS.sleep(2);}catch(InterruptedException e){}// 让 D 线程读取到 第一版数据
System.out.println(Thread.currentThread().getName()+" 结果 "+ sref.compareAndSet(1,127, sref.getStamp(), sref.getStamp()+1));
System.out.println(Thread.currentThread().getName()+" 第一次修改之后的版本 : "+ sref.getStamp());
System.out.println(Thread.currentThread().getName()+" 结果 "+ sref.compareAndSet(127,1, sref.getStamp(), sref.getStamp()+1));
System.out.println(Thread.currentThread().getName()+" 第二次修改之后的版本 : "+ sref.getStamp());},"C").start();newThread(()->{int stamp = sref.getStamp();//注意这个变量
System.out.println(Thread.currentThread().getName()+" 初始版本 =》 "+ stamp);try{ TimeUnit.SECONDS.sleep(5);}catch(InterruptedException e){}// 让C线程 将数据改为原先值
System.out.println(Thread.currentThread().getName()+" 结果 "+ sref.compareAndSet(1,127, stamp, stamp +1));},"D").start();}}