CAS:
CAS是英文单词Compare And Swap的缩写,翻译过来就是比较并替换
CAS的三个基本参数:
内存值,预估值与更新值
具体流程为:
线程2在读取变量i时,读取的预估值为0,但是此时线程1把i改成了1,主内存的i值为1.所以内存值与预估值不一样,需要重新读取在进行操作。
当内存值与预估值不一样的时候,就会取消操作,重新读取,确保变量一致
下面我们简单用代码实现一下CAS:
package com.jym.thread;
import java.util.Random;
/**
* @program: thread
* @description: CAS学习
* @author: jym
* @create: 2020/01/28
*/
public class JymCASTest {
public static void main(String[] args) {
final JymCAS jymCAS = new JymCAS();
for (int i =0;i<10;i++){
new Thread(new Runnable() {
public void run() {
//获取内存值
int expectValue = jymCAS.getValue();
System.out.println(expectValue);
boolean flag = jymCAS.compilerAndSet(expectValue, new Random().nextInt(100));
System.out.println(flag);
}
}).start();
}
}
}
class JymCAS {
private int value;
public int getValue() {
return value;
}
public synchronized int compilerAndSwap(int expectValue ,int newValue){
int oldValue = this.value;
// 内存值与预期值一样,进行赋值操作
if(oldValue==expectValue){
this.value = newValue;
}
return oldValue;
}
// 当预期值与内存值相等,说明赋值成功了
public boolean compilerAndSet(int expectValue ,int newValue){
return expectValue==compilerAndSwap(expectValue,newValue);
}
}