6.4.1 CAS是什么
CAS是CompareAndSwap的缩写,作用是比较与交换。
线程对变量的读取赋值等操作,要先将变量从主内存拷贝自己线程的工作内存空间,在工作内存中进行操作,操作完成后再将变量写回主内存
package com.javaliao.backstage;
import java.util.concurrent.atomic.AtomicInteger;
public class Demo {
//主线程main,程序入口
public static void main(String[] args) {
//原子类整型,在主内存中创建这个对象给初始值为5,默认初始值为0
AtomicInteger atomicInteger = new AtomicInteger(5);
//当线程中的工作内存要写回主内存时,拿第一个参数作为期望值和主内存中的值进行比较,如果期望值和主内存中的值相同都为5,更新值主内存中的值为2019
System.out.println(atomicInteger.compareAndSet(5, 2019)+"\t : "+ atomicInteger.get());
//线程a
new Thre