• Java AtomicInteger


    AtomicInteger,一个提供原子操作的Integer的类。在Java语言中,++i和i++操作并不是线程安全的,在使用的时候,不可避免的会用到synchronized关键字。而AtomicInteger则通过一种线程安全的加减操作接口。

    来看AtomicInteger提供的接口。

    //获取当前的值

    public final int get()

    //取当前的值,并设置新的值

     public final int getAndSet(int newValue)

    //获取当前的值,并自增

     public final int getAndIncrement()

    //获取当前的值,并自减

    public final int getAndDecrement()

    //获取当前的值,并加上预期的值

    public final int getAndAdd(int delta)

    ... ...

    我们在上一节提到的CAS主要是这两个方法

        public final boolean compareAndSet(int expect, int update) {
        return unsafe.compareAndSwapInt(this, valueOffset, expect, update);
        }

        public final boolean weakCompareAndSet(int expect, int update) {
        return unsafe.compareAndSwapInt(this, valueOffset, expect, update);
        }

    这两个方法是名称不同,但是做的事是一样的,可能在后续的java版本里面会显示出区别来。

    详细查看会发现,这两个接口都是调用一个unsafe的类来操作,这个是通过JNI实现的本地方法,细节就不考虑了。

     

    下面是一个对比测试,我们写一个synchronized的方法和一个AtomicInteger的方法来进行测试,直观的感受下性能上的差异

     

     
    1. package zl.study.concurrency;  
    2. import java.util.concurrent.atomic.AtomicInteger;  
    3. public class AtomicIntegerCompareTest {  
    4.     private int value;  
    5.       
    6.     public AtomicIntegerCompareTest(int value){  
    7.         this.value = value;  
    8.     }  
    9.       
    10.     public synchronized int increase(){  
    11.         return value++;  
    12.     }  
    13.       
    14.     public static void main(String args[]){  
    15.         long start = System.currentTimeMillis();  
    16.           
    17.         AtomicIntegerCompareTest test = new AtomicIntegerCompareTest(0);  
    18.         for( int i=0;i< 1000000;i++){  
    19.             test.increase();  
    20.         }  
    21.         long end = System.currentTimeMillis();  
    22.         System.out.println("time elapse:"+(end -start));  
    23.           
    24.         long start1 = System.currentTimeMillis();  
    25.           
    26.         AtomicInteger atomic = new AtomicInteger(0);  
    27.           
    28.         for( int i=0;i< 1000000;i++){  
    29.             atomic.incrementAndGet();  
    30.         }  
    31.         long end1 = System.currentTimeMillis();  
    32.         System.out.println("time elapse:"+(end1 -start1) );  
    33.           
    34.           
    35.     }  
    36. }  
  • 相关阅读:
    ASP.NET MVC使用Bootstrap系列(3)——使用Bootstrap 组件
    ASP.NET MVC使用Bootstrap系统(2)——使用Bootstrap CSS和HTML元素
    ASP.NET MVC使用Bootstrap系列(1)——开始使用Bootstrap
    C# 调用颜色的RGB值_RGB颜色转换十六进制颜色
    在C#中,Json的序列化和反序列化的几种方式总结
    Newtonsoft.Json(Json.Net)学习笔记
    C#,WebRequest类、HttpWebRequest类与HttpRequest类的区别
    python遍历目录的方法 walk listdir
    Debug始于71年前
    如何实现前端微服务化
  • 原文地址:https://www.cnblogs.com/justuntil/p/4704988.html
Copyright © 2020-2023  润新知