JUC篇之CAS算法(三 )
CAS算法
1、CAS(Compare-And-Swap)是一种硬件对并发的支持,针对多处理器操作而设计的处理器中的一种特殊指令,用于管理对共享数据的并发访问
2、CAS是一种无锁的非阻塞的算法的实现。
3、CAS包含了三个操作数
需要读写的内存值V
需要比较的值A
写入的新值B
4、当且仅当V的值等于A时,CAS的院子方式用新值B来更新V的值,否则不会执行任何操作。
5、核心方法 boolean compareAndSwap(expectValue,updateValue)
6、单个变量类:AtomicBoolean、AtomicInteger、AtomicReference、AtomicLong;
数组变量类:AtomicIntegerArray、AtomicLongArray、AtomicRefenceArray
代码模拟一下CAS算法
//创建一个对象,对该对象的一个int变量进行算法。创建十个线程操作进行模拟操作CAS算法,应为CAS算法是硬件对并发的支持,这里用synchronized代替这个支持。上代码
public class TestCompareAndSwap{
CompareAndSwapDemo compareAndSwapDemo = new CompareAndSwapDemo();
for(int i=0;i<=9;i++){
new Thread(new Runnable{
@Override4
private void run(){
//获取内存值
int expectValue = compareAndSwapDemo.get();
boolean b = compareAndSwapDemo.compareAndSwapSet(expectValue,((int)Math.random)*100);
System.out.println(b);
}
})
}
}
class CompareAndSwapDemo{
private int value;
//获取内存值方法
public int get(){
return value;
}
//比较值
public synchronized int compareAndSwap(int expectValue,int updateValue){
int oldValue = value;
if(oldValue == expectValue){
value = updateValue;
}
return oldValue;
}
// 设置
public synchronized boolean compareAndSet(int expectValue,int updateValue){
return expectValue = compareAndSwap(expectValue,updateValue);
}
}