Java多線程之LongAdder&AtomicInteger&synchronized比較基礎篇

一、前言

  • 爲什麼高併發下多個線程操作同一個變量會引發發線程安全問題,其本質原因在於count++count--a = a + b等等之類的操作不是原子性操作而LongAdderAtomicIntegersynchronized能夠保證操作的原子性

二、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();
        }
        /*此列用CountDownLatch的目的是爲了保證此條輸出語句最後執行*/
        System.out.println(longAdder);

    }
}

三、三者的比較

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章