在Java多线程编程中,多个线程同时修改同一个计数器变量时,会因为指令重排、内存可见性等问题导致计数结果不准确,因此实现多线程安全的计数器是并发编程的基础需求,下面介绍几种常用的实现方式。

使用synchronized关键字实现
synchronized是Java内置的同步机制,通过对代码块或方法加锁,保证同一时间只有一个线程能执行计数操作,是最基础的线程安全实现方式。
public class SynchronizedCounter {
private int count = 0;
// 对方法加锁,保证同一时间只有一个线程能执行该方法
public synchronized void increment() {
count++;
}
// 获取当前计数值
public synchronized int getCount() {
return count;
}
public static void main(String[] args) throws InterruptedException {
SynchronizedCounter counter = new SynchronizedCounter();
// 创建10个线程同时执行计数操作
Thread[] threads = new Thread[10];
for (int i = 0; i < 10; i++) {
threads[i] = new Thread(() -> {
for (int j = 0; j < 1000; j++) {
counter.increment();
}
});
threads[i].start();
}
// 等待所有线程执行完成
for (Thread thread : threads) {
thread.join();
}
System.out.println("最终计数结果:" + counter.getCount());
}
}使用ReentrantLock互斥锁实现
ReentrantLock是Java并发包提供的显式锁,相比synchronized更灵活,支持尝试获取锁、可中断获取锁等特性,同样可以实现计数器的线程安全。
import java.util.concurrent.locks.ReentrantLock;
public class LockCounter {
private int count = 0;
private final ReentrantLock lock = new ReentrantLock();
public void increment() {
lock.lock();
try {
count++;
} finally {
// 必须在finally块中释放锁,避免异常导致锁无法释放
lock.unlock();
}
}
public int getCount() {
lock.lock();
try {
return count;
} finally {
lock.unlock();
}
}
public static void main(String[] args) throws InterruptedException {
LockCounter counter = new LockCounter();
Thread[] threads = new Thread[10];
for (int i = 0; i < 10; i++) {
threads[i] = new Thread(() -> {
for (int j = 0; j < 1000; j++) {
counter.increment();
}
});
threads[i].start();
}
for (Thread thread : threads) {
thread.join();
}
System.out.println("最终计数结果:" + counter.getCount());
}
}使用AtomicInteger原子类实现
AtomicInteger是java.util.concurrent.atomic包下的原子类,基于CAS(比较并交换)机制实现,不需要加锁就能保证操作的原子性,性能比锁机制更好。
import java.util.concurrent.atomic.AtomicInteger;
public class AtomicCounter {
private final 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[] threads = new Thread[10];
for (int i = 0; i < 10; i++) {
threads[i] = new Thread(() -> {
for (int j = 0; j < 1000; j++) {
counter.increment();
}
});
threads[i].start();
}
for (Thread thread : threads) {
thread.join();
}
System.out.println("最终计数结果:" + counter.getCount());
}
}高并发场景使用LongAdder实现
如果是在高并发场景下,LongAdder的性能会比AtomicInteger更好,它采用分段计数的思路,减少CAS操作的竞争,适合写多读少的场景。
import java.util.concurrent.atomic.LongAdder;
public class LongAdderCounter {
private final LongAdder count = new LongAdder();
public void increment() {
count.increment();
}
public long getCount() {
return count.sum();
}
public static void main(String[] args) throws InterruptedException {
LongAdderCounter counter = new LongAdderCounter();
Thread[] threads = new Thread[10];
for (int i = 0; i < 10; i++) {
threads[i] = new Thread(() -> {
for (int j = 0; j < 1000; j++) {
counter.increment();
}
});
threads[i].start();
}
for (Thread thread : threads) {
thread.join();
}
System.out.println("最终计数结果:" + counter.getCount());
}
}不同方案对比
可以通过下面的表格了解不同实现方案的特点,方便根据场景选择:
| 实现方案 | 底层原理 | 性能表现 | 适用场景 |
|---|---|---|---|
| synchronized | JVM内置监视器锁 | 低并发下尚可,高并发竞争激烈时性能较差 | 低并发、简单的同步场景 |
| ReentrantLock | 显式互斥锁,AQS实现 | 和synchronized接近,灵活性更高 | 需要尝试获取锁、可中断锁等高级特性的场景 |
| AtomicInteger | CAS自旋机制 | 无锁,性能优于锁机制 | 中等并发、需要原子操作的场景 |
| LongAdder | 分段计数,减少竞争 | 高并发下性能最优 | 高并发写多读少的计数场景 |
注意事项
- 如果使用锁机制实现,一定要保证锁的释放,避免死锁问题,synchronized会自动释放锁,ReentrantLock需要手动在finally块中释放。
- AtomicInteger的incrementAndGet方法是原子操作,不需要额外加锁,不要重复加锁导致性能浪费。
- LongAdder的sum方法在调用时才会汇总各个段的值,如果期间有线程继续修改,可能得到近似值,如果需要精确值可以在汇总时暂停写入。
Java多线程安全计数器AtomicIntegersynchronized修改时间:2026-06-06 00:22:47