欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

詳細(xì)總結(jié)Java中常用的原子類

 更新時(shí)間:2021年05月26日 16:07:04   作者:it00zyq  
今天給大家總結(jié)了一下Java常用的原子類,文中有非常詳細(xì)的介紹及代碼示例,對正在學(xué)習(xí)java的小伙伴們很有幫助,需要的朋友可以參考下

一、什么是原子類

Java中提供了一些原子類,原子類包裝了一個(gè)變量,并且提供了一系列對變量進(jìn)行原子性操作的方法。我們在多線程環(huán)境下對這些原子類進(jìn)行操作時(shí),不需要加鎖,大大簡化了并發(fā)編程的開發(fā)。

二、原子類的底層實(shí)現(xiàn)

目前Java中提供的原子類大部分底層使用了CAS鎖(CompareAndSet自旋鎖),如AtomicInteger、AtomicLong等;也有使用了分段鎖+CAS鎖的原子類,如LongAdder等。

三、常用的原子類

3.1 AtomicInteger與AtomicLong

AtomicInteger與AtomicLong的底層實(shí)現(xiàn)與用法基本相同,不同點(diǎn)在于AtomicInteger包裝了一個(gè)Integer型變量,而AtomicLong包裝了一個(gè)Long型變量。
AtomicInteger與AtomicLong的底層實(shí)現(xiàn)都使用了CAS鎖。

import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;

/**
 * @author IT00ZYQ
 * @date 2021/5/24 15:33
 **/
public class T13_AtomicInteger {
    private static AtomicInteger atomicInteger = new AtomicInteger();
    private static AtomicLong atomicLong = new AtomicLong();
    private static Integer integer = 0;
    private static Long lon = 0L;
    public static void main(String[] args) {

        // 創(chuàng)建10個(gè)線程,分別對atomicInteger、atomicLong、integer、lon進(jìn)行1000次增加1的操作
        // 如果操作是原子性的,那么正確結(jié)果 = 10 * 1000 = 10000
        Thread[] threads = new Thread[10];
        for (int i = 0; i < 10; i++) {
            threads[i] = new Thread(() -> {
                for (int j = 1; j <= 1000; j++) {
                    atomicInteger.incrementAndGet();
                    atomicLong.incrementAndGet();
                    integer ++;
                    lon ++;
                }
            });
        }

        // 啟動(dòng)線程
        for (Thread thread : threads) {
            thread.start();
        }

        // 保證10個(gè)線程運(yùn)行完成
        try {
            for (Thread thread : threads) {
                thread.join();
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("AtomicInteger的結(jié)果:" + atomicInteger);
        System.out.println("AtomicLong的結(jié)果:" + atomicLong);
        System.out.println("Integer的結(jié)果:" + integer);
        System.out.println("Long的結(jié)果:" + lon);
    }
}

運(yùn)行結(jié)果:

AtomicInteger的結(jié)果:10000
AtomicLong的結(jié)果:10000
Integer的結(jié)果:4880
Long的結(jié)果:4350
Process finished with exit code 0

多次運(yùn)行發(fā)現(xiàn)原子類AtomicInteger與AtomicLong每次都能得到正確的結(jié)果10000,但是非原子類Integer與Long一般情況下都達(dá)不到10000,每次的結(jié)果也可能不一樣。

3.2 LongAdder

LongAdder的底層實(shí)現(xiàn)使用了分段鎖,每個(gè)段使用的鎖是CAS鎖,所以LongAdder的底層實(shí)現(xiàn)是分段鎖+CAS鎖。
在上面的程序添加了一個(gè)LongAdder變量進(jìn)行測試

import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.LongAdder;

/**
 * @author IT00ZYQ
 * @date 2021/5/24 15:33
 **/
public class T13_AtomicInteger {
    private static AtomicInteger atomicInteger = new AtomicInteger();
    private static AtomicLong atomicLong = new AtomicLong();
    private static LongAdder longAdder = new LongAdder();
    private static Integer integer = 0;
    private static Long lon = 0L;
    public static void main(String[] args) {

        // 創(chuàng)建10個(gè)線程,分別對atomicInteger、atomicLong、integer、lon進(jìn)行1000次增加1的操作
        // 如果操作是原子性的,那么正確結(jié)果 = 10 * 1000 = 10000
        Thread[] threads = new Thread[10];
        for (int i = 0; i < 10; i++) {
            threads[i] = new Thread(() -> {
                for (int j = 1; j <= 1000; j++) {
                    atomicInteger.incrementAndGet();
                    atomicLong.incrementAndGet();
                    integer ++;
                    lon ++;
                    longAdder.increment();
                }
            });
        }

        // 啟動(dòng)線程
        for (Thread thread : threads) {
            thread.start();
        }

        // 保證10個(gè)線程運(yùn)行完成
        try {
            for (Thread thread : threads) {
                thread.join();
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("AtomicInteger的結(jié)果:" + atomicInteger);
        System.out.println("AtomicLong的結(jié)果:" + atomicLong);
        System.out.println("Integer的結(jié)果:" + integer);
        System.out.println("Long的結(jié)果:" + lon);
        System.out.println("LongAdder的結(jié)果:" + longAdder);
    }
}

運(yùn)行結(jié)果:

AtomicInteger的結(jié)果:10000
AtomicLong的結(jié)果:10000
Integer的結(jié)果:6871
Long的結(jié)果:6518
LongAdder的結(jié)果:10000
Process finished with exit code 0

LongAdder類也是能夠正確輸出結(jié)果的。

四、原子類的性能測試

4.1 測試程序

package juc;

import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.LongAdder;

/**
 * @author IT00ZYQ
 * @date 2021/5/24 15:51
 **/
public class T14_AtomicClassPerformance {
    private static AtomicLong atomicLong = new AtomicLong();
    private static LongAdder longAdder = new LongAdder();
    /**
     * 線程數(shù)
     */
    private static final int THREAD_COUNT = 100;
    /**
     * 每次線程循環(huán)操作次數(shù)
     */
    private static final int OPERATION_COUNT = 10000;

    public static void main(String[] args) {
        Thread[] threads = new Thread[THREAD_COUNT];

        
        // 創(chuàng)建對AtomicLong進(jìn)行操作的線程
        for (int i = 0; i < THREAD_COUNT; i++) {
            threads[i] = new Thread(() -> {
                for (int j = 0; j < OPERATION_COUNT; j++) {
                    atomicLong.incrementAndGet();
                }
            });
        }

        long start1 = System.currentTimeMillis();
        // 啟動(dòng)線程
        for (Thread thread : threads) {
            thread.start();
        }

        // 保證線程運(yùn)行完成
        try {
            for (Thread thread : threads) {
                thread.join();
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        long end1 = System.currentTimeMillis();


        // 創(chuàng)建對LongAdder進(jìn)行操作的線程
        for (int i = 0; i < THREAD_COUNT; i++) {
            threads[i] = new Thread(() -> {
                for (int j = 0; j < OPERATION_COUNT; j++) {
                    longAdder.increment();
                }
            });
        }

        long start2 = System.currentTimeMillis();
        // 啟動(dòng)線程
        for (Thread thread : threads) {
            thread.start();
        }

        // 保證線程運(yùn)行完成
        try {
            for (Thread thread : threads) {
                thread.join();
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        long end2 = System.currentTimeMillis();

        System.out.println("AtomicLong運(yùn)行時(shí)間: " + (end1 - start1) + "ms, 運(yùn)行結(jié)果:" + atomicLong);
        System.out.println("LongAdder運(yùn)行時(shí)間: " + (end2 - start2) + "ms, 運(yùn)行結(jié)果:" + longAdder);
    }

}

4.2 測試結(jié)果

THREAD_COUNT = 100, OPERATION_COUNT = 1000時(shí)的運(yùn)行結(jié)果

AtomicLong運(yùn)行時(shí)間: 40ms, 運(yùn)行結(jié)果:100000
LongAdder運(yùn)行時(shí)間: 57ms, 運(yùn)行結(jié)果:100000
Process finished with exit code 0

THREAD_COUNT = 100, OPERATION_COUNT = 10000時(shí)的運(yùn)行結(jié)果

AtomicLong運(yùn)行時(shí)間: 108ms, 運(yùn)行結(jié)果:1000000
LongAdder運(yùn)行時(shí)間: 85ms, 運(yùn)行結(jié)果:1000000
Process finished with exit code 0

THREAD_COUNT = 100, OPERATION_COUNT = 1000000時(shí)的運(yùn)行結(jié)果

AtomicLong運(yùn)行時(shí)間: 6909ms, 運(yùn)行結(jié)果:100000000
LongAdder運(yùn)行時(shí)間: 468ms, 運(yùn)行結(jié)果:100000000
Process finished with exit code 0

THREAD_COUNT = 10, OPERATION_COUNT = 1000000時(shí)的運(yùn)行結(jié)果

AtomicLong運(yùn)行時(shí)間: 788ms, 運(yùn)行結(jié)果:10000000
LongAdder運(yùn)行時(shí)間: 162ms, 運(yùn)行結(jié)果10000000
Process finished with exit code 0

4.3 結(jié)果分析

當(dāng)THREAD_COUNT * OPERATION_COUN足夠小時(shí),AtomicInteger的性能會(huì)略高于LongAdder,而隨著THREAD_COUNT * OPERATION_COUN的增加,LongAdder的性能更高,THREAD_COUNT * OPERATION_COUN足夠大時(shí),LongAdder的性能遠(yuǎn)高于AtomicInteger。

4.4 底層實(shí)現(xiàn)分析

  • AtomicLong的原子性自增操作,是通過CAS實(shí)現(xiàn)的。在競爭線程數(shù)較少且每個(gè)線程的運(yùn)行所需時(shí)間較短的情況下,這樣做是合適的。但是如果線程競爭激烈,會(huì)造成大量線程在原地打轉(zhuǎn)、不停嘗試去修改值,但是老是發(fā)現(xiàn)值被修改了,于是繼續(xù)自旋。 這樣浪費(fèi)了大量的CPU資源。
  • LongAdder在競爭激烈時(shí),多個(gè)線程并不會(huì)一直自旋來修改值,而是采用了分段的思想,各個(gè)線程會(huì)分散累加到自己所對應(yīng)的Cell[]數(shù)組的某一個(gè)數(shù)組對象元素中,而不會(huì)大家共用一個(gè),把不同線程對應(yīng)到不同的Cell中進(jìn)行修改,降低了對臨界資源的競爭。本質(zhì)上,是用空間換時(shí)間。

到此這篇關(guān)于詳細(xì)總結(jié)Java中常用的原子類的文章就介紹到這了,更多相關(guān)Java常用原子類內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論