AtomicInteger、AtomicLong可以理解为乐观锁,它们认为变量值是不会改变,等去设置值的时候去确认。这种方式适用于该变量值很少更改的情况下,否则性能适得其反。
CAS(乐观锁算法)的基本假设前提
CAS比较与交换的伪代码可以表示为:
do{
备份旧数据;
基于旧数据构造新数据;
}while(!CAS( 内存地址,备份的旧数据,新数据 ))
下面写了个多线程的例子:
package com.zc.thread;
import java.util.concurrent.atomic.AtomicInteger;
/**
* Created by Administrator on 2017/5/17.
*/
public class CountTest {
public static void main(String[] args) {
CountThread countThread = new CountThread();
for(int i = 0 ; i < 5 ; i ++){
new Thread(countThread).start();
}
}
static class CountThread implements Runnable{
private AtomicInteger atomicInteger = new AtomicInteger(0);
@Override
public void run() {
setAtomicValue(atomicInteger.get()+1);
}
public void setAtomicValue(int newValue){
boolean flag = false;
do {
int oldValue = atomicInteger.get();
System.out.println("当前线程:"+Thread.currentThread().getName()+",旧的值:"+oldValue+",新的值:"+newValue);
flag = atomicInteger.compareAndSet(oldValue, newValue);
System.out.println("当前线程:"+Thread.currentThread().getName()+",原子的值设置结果:"+flag);
}while (!flag);
}
}
}
运行结果
发现红色圈的区域了吧,由于多线程,导致 Thread-3的线程将值设为1的时候失败,原因是0已经被Thread-0的线程设置为1了。所以Thread-3的线程设置失败,最后循环重新取出了最新的值1,然后Thread-3将值继续设置为1,返回true。