文章22 | 阅读 8036 | 点赞0
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 内部通过分段锁实现,在线程数特别多的时候很有优势。
版权说明 : 本文为转载文章, 版权归原作者所有 版权申明
原文链接 : https://blog.csdn.net/weixin_41685207/article/details/111084647
内容来源于网络,如有侵权,请联系作者删除!