package com.yellow.cas;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicStampedReference;
public class ABATest3 {
public static void main(String[] args) throws InterruptedException {
//创建一个原子Integer类型值为100
final AtomicInteger atomicInteger = new AtomicInteger(100);
//为了解决ABA问题使用jdk提供的 AtomicStampedReference
final AtomicStampedReference<Integer> reference = new AtomicStampedReference<Integer>(100, 0);
//创建一个线程t1
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
//改变atomicInteger的值为200,并打印修改值是否成功
boolean flag = reference.compareAndSet(100, 200, reference.getStamp(), reference.getStamp() + 1);
System.out.println("t1:" + flag);
}
});
//创建一个线程t2
Thread t2 = new Thread(new Runnable() {
@Override
public void run() {
//改变atomicInteger的值为300,并打印修改值是否成功
reference.compareAndSet(100, 101, reference.getStamp(), reference.getStamp() + 1);
boolean flag = reference.compareAndSet(101 ,100, reference.getStamp(), reference.getStamp() + 1);
System.out.println("t2:" + flag);
}
});
t1.start();
t2.start();
// 让t2先执行
t2.join();
}
}
|
|