java.util.concurrent.atomic 提供無鎖線程安全操作:
AtomicInteger、AtomicLong、AtomicBoolean、AtomicReferenceAtomicIntegerArray 等AtomicIntegerFieldUpdater 等LongAdder (Java 8) 高並發優於 AtomicLong核心方法:getAndIncrement()、addAndGet(delta)、compareAndSet(expect, update) (CAS)。
class MyRunnable implements Runnable {
private static AtomicLong aLong = new AtomicLong(10000);
private String name; private int x;
MyRunnable(String name, int x) { this.name = name; this.x = x; }
public void run() {
System.out.println(name + "執行了" + x + ",當前余額:" + aLong.addAndGet(x));
}
}
// 多線程運行,最終餘額可能不等於 10000 + 2000+3600+2700+600+1300+800 = 21000
多次運行結果不一,最終餘額可能 21000、15600、18300 等。原因:addAndGet 單操作原子,但 System.out.println 非原子,多線程交替導致讀取值不一致。
class MyRunnable implements Runnable {
private static AtomicLong aLong = new AtomicLong(10000);
private String name; private int x; private Lock lock;
MyRunnable(String name, int x, Lock lock) {
this.name = name; this.x = x; this.lock = lock;
}
public void run() {
lock.lock();
try {
System.out.println(name + "執行了" + x + ",當前余額:" + aLong.addAndGet(x));
} finally { lock.unlock(); }
}
}
// 多次運行最終餘額恆為 21000
LongAdder,分段累加極大減少 CAS 競爭compareAndSet 失敗需重試,極高爭用下性能下降| 場景 | 推薦方案 |
|---|---|
| 簡單計數器、統計指標 | AtomicLong / LongAdder |
| 單一共享對象引用更新 | AtomicReference |
| 復合業務邏輯(轉賬、庫存扣減) | Lock / synchronized + 原子變量 |
| 無鎖數據結構實現 | CAS + volatile 組合 |