蘇阿細 - Unsafe
type: channel
link: https://www.wangchouchou.com/tag/Unsafe/
items: CompareAndSet(CAS)

CompareAndSet(CAS)
type: item
date: 2021-02-21T14:54:00+00:00
description: CompareAndSet(CAS)CASCAS：比较并交换package com.sw.cas; import java.util.concurrent.atomic.AtomicInteger; /** * @Author suaxi * @Date 2021/2/21 20:58 * CAS:比较并交换 */ public class casTest { public static void main(String[] args) { AtomicInteger atomicInteger = new AtomicInteger(2021); //如果达到期望的值，就更新，否则反之 System.out.println(atomicInteger.compareAndSet(2021,666)); //true System.out.println(atomicInteger.get()); //666 } } Unsafe图片来源：狂神说Java缺点：1、循环会耗时2、一次循环只能保证一个共享变量的原子性3、ABA问题ABA问题package com.sw.cas; import java.util.concurrent.atomic.AtomicInteger; /** * @Author suaxi * @Date 2021/2/21 20:58 * CAS:比较并交换 */ public class casTest { public static void main(String[] args) { AtomicInteger atomicInteger = new AtomicInteger(2021); //如果达到期望的值，就更新，否则反之 //捣乱的线程 System.out.println(atomicInteger.compareAndSet(2021,666)); //true System.out.println(atomicInteger.get()); //666 System.out.println(atomicInteger.compareAndSet(666,2021)); System.out.println(atomicInteger.get()); //期望的线程 System.out.println(atomicInteger.compareAndSet(2021, 888)); System.out.println(atomicInteger.get()); } }