AtomicInteger 使用案例
AtomicInteger 是 Java 并发包中的原子类,提供线程安全的整数操作,下面从基础到实战逐步介绍使用案例。

基础用法
import java.util.concurrent.atomic.AtomicInteger;
public class AtomicIntegerBasic {
public static void main(String[] args) {
// 创建 AtomicInteger
AtomicInteger counter = new AtomicInteger();
// 基本操作
counter.set(10); // 设置值
System.out.println(counter.get()); // 获取值: 10
// 递增递减
System.out.println(counter.incrementAndGet()); // 先增后取: 11
System.out.println(counter.getAndIncrement()); // 先取后增: 11 (实际值变为12)
System.out.println(counter.decrementAndGet()); // 先减后取: 11
// 加减操作
System.out.println(counter.addAndGet(5)); // 加5后返回: 16
System.out.println(counter.getAndAdd(3)); // 返回原值再+3: 16 (实际值19)
// 比较并交换 (CAS)
boolean success = counter.compareAndSet(19, 100);
System.out.println("CAS 成功: " + success + ", 当前值: " + counter.get());
}
}
计数器案例(最常用)
import java.util.concurrent.atomic.AtomicInteger;
public class CounterExample {
private static AtomicInteger visitCount = new AtomicInteger(0);
public static void main(String[] args) throws InterruptedException {
// 模拟 10 个线程同时访问
for (int i = 0; i < 10; i++) {
new Thread(() -> {
for (int j = 0; j < 1000; j++) {
visitor(); // 每次访问+1
}
}).start();
}
Thread.sleep(1000); // 等待所有线程执行完毕
System.out.println("总访问次数: " + visitCount.get()); // 输出: 10000
}
public static void visitor() {
visitCount.incrementAndGet(); // 线程安全的自增
}
}
限流器案例
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.TimeUnit;
public class RateLimiter {
private final int maxRequests;
private final long timeWindow;
private final AtomicInteger count = new AtomicInteger(0);
private volatile long windowStart = System.currentTimeMillis();
public RateLimiter(int maxRequests, long timeWindow, TimeUnit unit) {
this.maxRequests = maxRequests;
this.timeWindow = unit.toMillis(timeWindow);
}
public boolean tryAcquire() {
long currentTime = System.currentTimeMillis();
// 如果超出时间窗口,重置计数器
if (currentTime - windowStart > timeWindow) {
synchronized (this) {
if (currentTime - windowStart > timeWindow) {
count.set(0);
windowStart = currentTime;
}
}
}
// 尝试增加计数
int currentCount = count.incrementAndGet();
if (currentCount > maxRequests) {
count.decrementAndGet(); // 超过限制,回滚
return false;
}
return true;
}
public static void main(String[] args) throws InterruptedException {
// 每秒最多允许 3 个请求
RateLimiter limiter = new RateLimiter(3, 1, TimeUnit.SECONDS);
for (int i = 0; i < 10; i++) {
boolean allowed = limiter.tryAcquire();
System.out.println("请求 " + (i+1) + ": " + (allowed ? "允许" : "拒绝"));
}
}
}
唯一ID生成器
import java.util.concurrent.atomic.AtomicInteger;
public class IdGenerator {
private static final AtomicInteger counter = new AtomicInteger(0);
private static final int MAX_VALUE = 999999;
public static String generateOrderId() {
// 循环重置,避免溢出
while (true) {
int current = counter.get();
int next = current >= MAX_VALUE ? 0 : current + 1;
if (counter.compareAndSet(current, next)) {
return String.format("%s%06d", "ORDER", next);
}
}
}
public static void main(String[] args) {
for (int i = 0; i < 5; i++) {
System.out.println(generateOrderId());
}
}
}
性能对比(synchronized vs AtomicInteger)
import java.util.concurrent.atomic.AtomicInteger;
public class PerformanceCompare {
private static int syncCount = 0;
private static AtomicInteger atomicCount = new AtomicInteger(0);
public static void main(String[] args) throws InterruptedException {
// AtomicInteger 性能测试
long start = System.currentTimeMillis();
Thread[] threads = new Thread[100];
for (int i = 0; i < 100; i++) {
threads[i] = new Thread(() -> {
for (int j = 0; j < 10000; j++) {
atomicCount.incrementAndGet();
}
});
threads[i].start();
}
for (Thread t : threads) t.join();
System.out.println("AtomicInteger: " + (System.currentTimeMillis() - start) + "ms");
// synchronized 性能测试
start = System.currentTimeMillis();
for (int i = 0; i < 100; i++) {
threads[i] = new Thread(() -> {
for (int j = 0; j < 10000; j++) {
synchronized (PerformanceCompare.class) {
syncCount++;
}
}
});
threads[i].start();
}
for (Thread t : threads) t.join();
System.out.println("synchronized: " + (System.currentTimeMillis() - start) + "ms");
}
}
常用方法总结
| 方法 | 描述 |
|---|---|
get() |
获取当前值 |
set(int) |
设置值 |
getAndSet(int) |
返回旧值并设置新值 |
incrementAndGet() |
先加1再返回 |
getAndIncrement() |
先返回再加1 |
addAndGet(int) |
先加指定值再返回 |
getAndAdd(int) |
先返回再加指定值 |
compareAndSet(int, int) |
CAS操作,成功返回true |
updateAndGet(UnaryOperator) |
使用函数更新并返回新值 |
使用建议
- 适合场景:简单的计数器、序列生成、统计等
- 不适合场景:复杂的状态管理、需要多个变量原子性操作的场景
- 注意事项:CAS 在竞争激烈时可能导致自旋消耗 CPU
AtomicInteger 通过硬件级别的 CAS 操作提供比 synchronized 更好的性能,特别适合简单的并发计数场景。