2026/1/9 22:28:49
网站建设
项目流程
江门网站建设,微信商城公众号,昆明建设网站哪家好,浙江三建建设集团有限公司网站一、Compare-And-Swap 是CPU提供的一种原子指令是无锁并发算法的基础#xff0c;适合读多写少、竞争不激烈的场景二、核心思想比较内存中的某个值是否为预期值#xff0c;如果是#xff0c;则更新为新值#xff0c;否则不做修改。这个操作是原子性的。三、工作原理Compare比…一、Compare-And-Swap是CPU提供的一种原子指令是无锁并发算法的基础适合读多写少、竞争不激烈的场景二、核心思想比较内存中的某个值是否为预期值如果是则更新为新值否则不做修改。这个操作是原子性的。三、工作原理Compare比较CAS会检查内存中的某个值是否与期望值相等。Swap交换如果相等则将内存中的值更新为新值。失败重试如果不相等说明其他线程已经修改了该值CAS操作失败一般会利用重试直到成功。四、CAS的优点无锁并发CAS操作不使用锁因此不会导致线程阻塞提高了系统的并发性和性能。原子性CAS操作是原子的保证了线程安全。五、CAS的缺点ABA问题CAS操作中如果一个变量值从A变成B又变回ACAS无法检测到这种变化可能导致错误。解决方案引入版本号或时间戳自旋开销CAS通过自旋实现可能导致CPU资源浪费尤其在高并发情况下。单变量限制CAS操作仅适用于单个变量的更新不适用于涉及多个变量的复杂操作。六、在Java中的具体实现Atomic原子类import java.util.concurrent.atomic.AtomicInteger; public class AtomicDemo1 { // 基本类型原子类 private AtomicInteger atomicInt new AtomicInteger(0); public void method1(){ // 标准的CAS使用方式 int oldValue, newValue; do { oldValue atomicInt.get(); newValue oldValue 1; System.out.println(Thread.currentThread().getName() --oldValue: oldValue newValue: newValue); } while (!atomicInt.compareAndSet(oldValue, newValue)); // 内置方法 // atomicInt.decrementAndGet(); } public static void main(String[] args) throws InterruptedException { AtomicDemo1 atomicDemo1 new AtomicDemo1(); Thread thread1 new Thread(() - { atomicDemo1.method1(); try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } }, 线程1); Thread thread2 new Thread(() - { atomicDemo1.method1(); },线程2); thread1.start(); thread2.start(); } }