欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

详细总结Java中常用的原子类

程序员文章站 2022-04-22 23:26:46
一、什么是原子类java中提供了一些原子类,原子类包装了一个变量,并且提供了一系列对变量进行原子性操作的方法。我们在多线程环境下对这些原子类进行操作时,不需要加锁,大大简化了并发编程的开发。二、原子类...

一、什么是原子类

java中提供了一些原子类,原子类包装了一个变量,并且提供了一系列对变量进行原子性操作的方法。我们在多线程环境下对这些原子类进行操作时,不需要加锁,大大简化了并发编程的开发。

二、原子类的底层实现

目前java中提供的原子类大部分底层使用了cas锁(compareandset自旋锁),如atomicinteger、atomiclong等;也有使用了分段锁+cas锁的原子类,如longadder等。

三、常用的原子类

3.1 atomicinteger与atomiclong

atomicinteger与atomiclong的底层实现与用法基本相同,不同点在于atomicinteger包装了一个integer型变量,而atomiclong包装了一个long型变量。
atomicinteger与atomiclong的底层实现都使用了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) {

        // 创建10个线程,分别对atomicinteger、atomiclong、integer、lon进行1000次增加1的操作
        // 如果操作是原子性的,那么正确结果 = 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 ++;
                }
            });
        }

        // 启动线程
        for (thread thread : threads) {
            thread.start();
        }

        // 保证10个线程运行完成
        try {
            for (thread thread : threads) {
                thread.join();
            }
        } catch (interruptedexception e) {
            e.printstacktrace();
        }

        system.out.println("atomicinteger的结果:" + atomicinteger);
        system.out.println("atomiclong的结果:" + atomiclong);
        system.out.println("integer的结果:" + integer);
        system.out.println("long的结果:" + lon);
    }
}

运行结果:

atomicinteger的结果:10000
atomiclong的结果:10000
integer的结果:4880
long的结果:4350
process finished with exit code 0

多次运行发现原子类atomicinteger与atomiclong每次都能得到正确的结果10000,但是非原子类integer与long一般情况下都达不到10000,每次的结果也可能不一样。

3.2 longadder

longadder的底层实现使用了分段锁,每个段使用的锁是cas锁,所以longadder的底层实现是分段锁+cas锁。
在上面的程序添加了一个longadder变量进行测试

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) {

        // 创建10个线程,分别对atomicinteger、atomiclong、integer、lon进行1000次增加1的操作
        // 如果操作是原子性的,那么正确结果 = 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();
                }
            });
        }

        // 启动线程
        for (thread thread : threads) {
            thread.start();
        }

        // 保证10个线程运行完成
        try {
            for (thread thread : threads) {
                thread.join();
            }
        } catch (interruptedexception e) {
            e.printstacktrace();
        }

        system.out.println("atomicinteger的结果:" + atomicinteger);
        system.out.println("atomiclong的结果:" + atomiclong);
        system.out.println("integer的结果:" + integer);
        system.out.println("long的结果:" + lon);
        system.out.println("longadder的结果:" + longadder);
    }
}

运行结果:

atomicinteger的结果:10000
atomiclong的结果:10000
integer的结果:6871
long的结果:6518
longadder的结果:10000
process finished with exit code 0

longadder类也是能够正确输出结果的。

四、原子类的性能测试

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();
    /**
     * 线程数
     */
    private static final int thread_count = 100;
    /**
     * 每次线程循环操作次数
     */
    private static final int operation_count = 10000;

    public static void main(string[] args) {
        thread[] threads = new thread[thread_count];

        
        // 创建对atomiclong进行操作的线程
        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();
        // 启动线程
        for (thread thread : threads) {
            thread.start();
        }

        // 保证线程运行完成
        try {
            for (thread thread : threads) {
                thread.join();
            }
        } catch (interruptedexception e) {
            e.printstacktrace();
        }
        long end1 = system.currenttimemillis();


        // 创建对longadder进行操作的线程
        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();
        // 启动线程
        for (thread thread : threads) {
            thread.start();
        }

        // 保证线程运行完成
        try {
            for (thread thread : threads) {
                thread.join();
            }
        } catch (interruptedexception e) {
            e.printstacktrace();
        }
        long end2 = system.currenttimemillis();

        system.out.println("atomiclong运行时间: " + (end1 - start1) + "ms, 运行结果:" + atomiclong);
        system.out.println("longadder运行时间: " + (end2 - start2) + "ms, 运行结果:" + longadder);
    }

}

4.2 测试结果

thread_count = 100, operation_count = 1000时的运行结果

atomiclong运行时间: 40ms, 运行结果:100000
longadder运行时间: 57ms, 运行结果:100000
process finished with exit code 0

thread_count = 100, operation_count = 10000时的运行结果

atomiclong运行时间: 108ms, 运行结果:1000000
longadder运行时间: 85ms, 运行结果:1000000
process finished with exit code 0

thread_count = 100, operation_count = 1000000时的运行结果

atomiclong运行时间: 6909ms, 运行结果:100000000
longadder运行时间: 468ms, 运行结果:100000000
process finished with exit code 0

thread_count = 10, operation_count = 1000000时的运行结果

atomiclong运行时间: 788ms, 运行结果:10000000
longadder运行时间: 162ms, 运行结果10000000
process finished with exit code 0

4.3 结果分析

thread_count * operation_coun足够小时,atomicinteger的性能会略高于longadder,而随着thread_count * operation_coun的增加,longadder的性能更高,thread_count * operation_coun足够大时,longadder的性能远高于atomicinteger。

4.4 底层实现分析

  • atomiclong的原子性自增操作,是通过cas实现的。在竞争线程数较少且每个线程的运行所需时间较短的情况下,这样做是合适的。但是如果线程竞争激烈,会造成大量线程在原地打转、不停尝试去修改值,但是老是发现值被修改了,于是继续自旋。 这样浪费了大量的cpu资源。
  • longadder在竞争激烈时,多个线程并不会一直自旋来修改值,而是采用了分段的思想,各个线程会分散累加到自己所对应的cell[]数组的某一个数组对象元素中,而不会大家共用一个,把不同线程对应到不同的cell中进行修改,降低了对临界资源的竞争。本质上,是用空间换时间。

到此这篇关于详细总结java中常用的原子类的文章就介绍到这了,更多相关java常用原子类内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!