AtomicReference类似于AtomicInteger AtomicBoolean这些对于数据的操作是原子操作在执行指令期间CPU 会锁定内存总线或缓存行其他任何线程都无法插手。要么整个操作成功完成要么完全不执行不会出现“执行了一半”的中间状态。用状态机的状态切换demo测试下package com.example.javalib; import java.util.concurrent.CountDownLatch; import java.util.concurrent.atomic.AtomicReference; public class TestAtomicReference { // 定义状态枚举 private enum State { INIT, RUNNING, STOPPED } // 使用 AtomicReference 管理状态初始为 INIT private static final AtomicReferenceState stateRef new AtomicReference(State.INIT); // 记录有多少个线程成功抢到了状态切换权 private static int successCount 0; public static void test() { int threadCount 10; CountDownLatch latch new CountDownLatch(threadCount); for (int i 0; i threadCount; i) { new Thread(() - { // 核心无锁状态切换逻辑 // 获取当前状态 // State currentState stateRef.get(); // 核心 CAS 操作比较并交换. 如果是INIT状态就切换为RUNNING boolean success stateRef.compareAndSet(State.INIT, State.RUNNING); if (success) { successCount; // 只有 CAS 成功的线程才会进入这里 System.out.println(Thread.currentThread().getName() 成功将状态切换为 RUNNING); } else { System.out.println(Thread.currentThread().getName() 切换失败状态已被其他线程修改); } latch.countDown(); }, Thread- i).start(); } try { latch.await(); // 阻塞等待计数器归零 } catch (InterruptedException e) { System.out.println(主线程被中断 e.getMessage()); Thread.currentThread().interrupt(); } System.out.println(); System.out.println(最终状态: stateRef.get()); System.out.println(成功切换的线程数: successCount); // 结果必定是 1 } }运行ok. 状态正常切换。