使用 atomicinteger 替代 volatile int 可以解决复合操作的原子性问题,例如自增或条件更新。具体做法是将变量类型改为 java.util.concurrent.atomic.atomicinteger,并将自增操作替换为 incrementandget() 方法,将比较并交换逻辑替换为 compareandset() 方法。这样做能保证在多线程环境下对整数的修改是原子的,避免了因线程调度导致的计数错误或状态不一致。

volatile 自增为什么不是原子的
volatile 只能保证变量的可见性和有序性,不能保证复合操作的原子性。当多个线程同时执行 i++ 时,会经历读取、修改、写入三个步骤,中间可能被其他线程打断,导致最终结果小于预期。要解决这个问题,必须引入原子类或锁机制。

import java.util.concurrent.atomic.AtomicInteger;
public class AtomicCounter {
private AtomicInteger count = new AtomicInteger(0);
public void increment() {
count.incrementAndGet();
}
public int getCount() {
return count.get();
}
public static void main(String[] args) throws InterruptedException {
AtomicCounter counter = new AtomicCounter();
Thread t1 = new Thread(() -> {
for (int i = 0; i {
for (int i = 0; i <p>运行上述代码,预期输出为 <code>Final Count: 2000</code>。如果使用 <code>volatile int</code> 和 <code>i++</code>,多次运行结果可能小于 2000。使用 <code>AtomicInteger</code> 后,由于 <code>incrementAndGet()</code> 基于 CAS 指令,保证了操作的原子性,结果始终正确。</p><h2>compareAndSet 如何实现条件更新</h2><p>除了自增,<code>AtomicInteger</code> 还提供了 <code>compareAndSet(expected, update)</code> 方法,用于实现条件更新。该方法先检查当前值是否等于期望值,如果是则更新为新值并返回 true,否则返回 false。这比使用 <code>synchronized</code> 块更高效,因为它避免了线程阻塞。</p><div class="aritcle_card flexRow artxards">
<div class="artcardd flexRow">
<a class="aritcle_card_img" rel="nofollow" href="/xiazai/skill13998" title="OpenAI Agents SDK JavaScript 工作流工具包"><img
src="https://img.php.cn/upload/skill/001/246/273/6adaf20d3191a227.jpg" alt="OpenAI Agents SDK JavaScript 工作流工具包" onerror="this.onerror='';this.src='/static/lhimages/moren/morentu.png'" ></a>
<div class="aritcle_card_info flexColumn">
<a rel="nofollow" href="/xiazai/skill13998" title="OpenAI Agents SDK JavaScript 工作流工具包" class="overflowclass">OpenAI Agents SDK JavaScript 工作流工具包</a>
<p class="overflowclass">一个基于源码的 OpenAI Agents SDK JavaScript 和 TypeScript 技术文档。涵盖了代理编排、工具、转接、追踪以及实际安装路径。</p>
</div>
<a rel="nofollow" href="/xiazai/skill13998" title="OpenAI Agents SDK JavaScript 工作流工具包" class="aritcle_card_btn flexRow flexcenter"><b></b><span>下载</span>
</a>
</div>
</div><p><img src="https://img.php.cn/upload/article/001/242/473/179558979052844.png?x-oss-process=image/resize,p_40" alt="Java volatile 怎么用 AtomicInteger 替代保证原子"></p><pre class="brush:php;toolbar:false;">import java.util.concurrent.atomic.AtomicInteger;
public class AtomicUpdater {
private AtomicInteger value = new AtomicInteger(0);
public boolean tryUpdate(int expected, int newValue) {
return value.compareAndSet(expected, newValue);
}
public static void main(String[] args) {
AtomicUpdater updater = new AtomicUpdater();
// 初始值为 0
boolean result1 = updater.tryUpdate(0, 10);
System.out.println("Result 1: " + result1); // true
System.out.println("Current Value: " + updater.value.get()); // 10
boolean result2 = updater.tryUpdate(0, 20); // 当前值是 10,不等于 0
System.out.println("Result 2: " + result2); // false
System.out.println("Current Value: " + updater.value.get()); // 仍为 10
}
}
运行上述代码,预期输出为:Result 1: trueCurrent Value: 10Result 2: falseCurrent Value: 10
这表明 compareAndSet 成功更新了值,而第二次调用因为期望值不匹配而失败,且值未被修改。这种机制常用于实现无锁数据结构或重试逻辑。
AtomicInteger 在并发累加中的表现
在并发累加场景中,AtomicInteger 的 addAndGet() 或 incrementAndGet() 方法能确保每个线程的累加操作都是原子的。与使用 synchronized 关键字相比,它减少了上下文切换的开销,提高了吞吐量。对于简单的计数器,这是首选方案。
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南










