、
CAS的原理是利用计算机的CAS指令根据旧地址把旧值和新值做一次更新
package cas;
import java.util.concurrent.atomic.AtomicStampedReference;
public class UseAtomicStampedReference {
static AtomicStampedReference<String> asr = new AtomicStampedReference<String>("mark", 0);
public static void main(String[] args) throws InterruptedException {
//拿到当前AtomicStampedReference版本号(初始值)
final int oldstamp = asr.getStamp();
//当前版本的值(初始值)
final String oldReference = asr.getReference();
//打印当前也就是初始值
System.out.println(oldReference+"============="+oldstamp);
//顶一个线程用于更新asrl里面的值和版本
Thread rightStampThread = new Thread(new Runnable() {
@Override
public void run() {
// asr.compareAndSet方法用来设置,第一个参数是旧值,第二个是新值,第三个是旧版本号,第四个是新版本号
System.out.println(Thread.currentThread().getName()+"当前变量值:"+oldReference+"-当前版本戳:"
+oldstamp+"-"+asr.compareAndSet(oldReference, oldReference+"whx", oldstamp, oldstamp+1));
}
});
// //最后一次更新我让他不成功,相当于是演示错误的更新
Thread errorStampThread = new Thread(new Runnable() {
@Override
public void run() {
//拿当前的值
String reference = asr.getReference();
// 注意:这里使用asr.compareAndSet方法第三个参数传入的是初始版本号,所以更新不到
System.out.println(Thread.currentThread().getName()+"当前变量值:"+reference+"-当前版本戳:"+
asr.getStamp()+"-"+asr.compareAndSet(reference, reference+"C",oldstamp,oldstamp+1));
}
});
rightStampThread.start();
rightStampThread.join();
errorStampThread.start();
errorStampThread.join();
System.out.println(asr.getReference()+"=============="+asr.getStamp());
}
}
打印结果为,发现第二次返回的是false说明更新失败:
mark=============0
Thread-0当前变量值:mark-当前版本戳:0-true
Thread-1当前变量值:markwhx-当前版本戳:1-false
markwhx==============1