AtomicLong VS Sync VS LongAdder
阿新 • • 發佈:2020-12-13
技術標籤:Java 併發程式設計java
AtomicLong VS Sync VS LongAdder
public class T02_AtomicVsSyncVsLongAdder {
static AtomicLong count1 = new AtomicLong(0L);
static Long count2 = 0L;
static LongAdder count3 = new LongAdder();
public static void main(String[] args) throws InterruptedException {
Thread[ ] threads = new Thread[1000];
long start, end;
// AtomicLong
for (int i = 0; i < threads.length; i++) {
threads[i] = new Thread(() -> {
for (int j = 0; j < 100000; j++) count1.incrementAndGet();
});
}
start = System.currentTimeMillis ();
for (Thread thread : threads) thread.start();
for (Thread thread : threads) thread.join();
end = System.currentTimeMillis();
System.out.println("Atomic " + count1 + " time " + (end - start));
// long
final Object lock = new Object ();
for (int i = 0; i < threads.length; i++) {
threads[i] = new Thread(new Runnable() {
@Override
public void run() {
for (int j = 0; j < 100000; j++) {
synchronized (lock) {
count2++;
}
}
}
});
}
start = System.currentTimeMillis();
for (Thread thread : threads) thread.start();
for (Thread thread : threads) thread.join();
end = System.currentTimeMillis();
System.out.println("Sync " + count2 + " time " + (end - start));
// LongAdder
for (int i = 0; i < threads.length; i++) {
threads[i] = new Thread(() -> {
for (int j = 0; j < 100000; j++) {
count3.increment();
}
});
}
start = System.currentTimeMillis();
for (Thread thread : threads) thread.start();
for (Thread thread : threads) thread.join();
end = System.currentTimeMillis();
System.out.println("LongAdder " + count3 + " time " + (end - start));
}
}
// 控制檯輸出如下
Atomic 100000000 time 944
Sync 100000000 time 7446
LongAdder 100000000 time 878
Atmoic 原子類是通過 CAS 演算法實現的。
LongAdder 為什麼最快?LongAdder 內部通過分段鎖實現,線上程數特別多的時候很有優勢。
[外鏈圖片轉存失敗,源站可能有防盜鏈機制,建議將圖片儲存下來直接上傳(img-pRnhxHPt-1607776451081)(https://gitee.com/itming1024/ImageBedOne/raw/master/img/IMG_0322(20201206-220357)].PNG)