一、前言
- 爲什麼高併發下多個線程操作同一個變量會引發發線程安全問題,其本質原因在於
count++
、count--
、a = a + b
等等之類的操作不是原子性操作而LongAdder
、AtomicInteger
、synchronized
能夠保證操作的原子性
二、LongAdder代碼示例
public class MyLongAdder {
private static LongAdder longAdder = new LongAdder();
private static Thread[] threads = new Thread[100];
private static CountDownLatch latch = new CountDownLatch(100);
public static void main(String[] args) {
for (int i = 0; i < threads.length; i++) {
threads[i] = new Thread(()->{
for (int j = 0; j < 100; j++) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
longAdder.increment();
}
latch.countDown();
});
}
for (Thread thread : threads) {
thread.start();
}
try {
latch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(longAdder);
}
}
三、三者的比較