AtomicInteger通过CAS机制实现线程安全的原子操作,提供incrementAndGet、getAndIncrement等方法,适用于高并发下的计数器场景,相比synchronized性能更高。

在多线程环境下,共享变量的自增、自减等操作可能引发线程安全问题。Java 提供了 AtomicInteger 类来解决这类问题,它通过底层的 CAS(Compare-And-Swap)机制保证操作的原子性,无需使用 synchronized 关键字即可实现高效、线程安全的操作。
什么是 AtomicInteger
AtomicInteger 是 java.util.concurrent.atomic 包中的一个类,它封装了一个 int 类型的值,并提供了一系列原子操作方法。与普通 int 变量不同,AtomicInteger 的 increment、decrement 和 add 等操作都是原子的,适合在高并发场景下使用。
常用方法及用法示例
以下是一些常用的 AtomicInteger 方法及其使用方式:
- get():获取当前值
- set(int newValue):设置新值
- incrementAndGet():先自增再返回结果(相当于 ++i)
- getAndIncrement():先返回当前值再自增(相当于 i++)
- decrementAndGet():先自减再返回
- getAndDecrement():先返回再自减
- addAndGet(int delta):加上指定值并返回结果
- compareAndSet(int expect, int update):如果当前值等于 expect,则更新为 update,成功返回 true
示例代码:
立即学习“Java免费学习笔记(深入)”;
import java.util.concurrent.atomic.AtomicInteger;
public class Counter {
private static AtomicInteger count = new AtomicInteger(0);
public static void increment() {
count.incrementAndGet(); // 原子自增
}
public static int getValue() {
return count.get();
}
}
多个线程调用 increment() 方法时,不会出现竞态条件,最终结果是准确的。
适用场景与优势
AtomicInteger 特别适用于计数器、序列号生成、状态标志等需要频繁读写的小范围整数操作。相比 synchronized,它的性能更高,因为基于硬件级别的 CAS 操作,避免了线程阻塞和上下文切换开销。
注意:虽然 CAS 高效,但在高竞争环境下可能出现“自旋”开销,即线程不断尝试更新直到成功。此时可考虑使用 LongAdder 等更高级的工具。
基本上就这些,AtomicInteger 使用简单且高效,是处理并发整数操作的首选方案。










