zoukankan      html  css  js  c++  java
  • AtomicInteger 一个提供原子操作的Integer类

    转自:http://www.blogjava.net/freeman1984/archive/2011/10/17/361402.html

    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的方法来进行测试,直观的感受下性能上的差异

    package zl.study.concurrency;  
    import java.util.concurrent.atomic.AtomicInteger;  
    public class AtomicIntegerCompareTest {  
        private int value;  
          
        public AtomicIntegerCompareTest(int value){  
            this.value = value;  
        }  
          
        public synchronized int increase(){  
            return value++;  
        }  
          
        public static void main(String args[]){  
            long start = System.currentTimeMillis();  
              
            AtomicIntegerCompareTest test = new AtomicIntegerCompareTest(0);  
            for( int i=0;i< 1000000;i++){  
                test.increase();  
            }  
            long end = System.currentTimeMillis();  
            System.out.println("time elapse:"+(end -start));  
              
            long start1 = System.currentTimeMillis();  
              
            AtomicInteger atomic = new AtomicInteger(0);  
              
            for( int i=0;i< 1000000;i++){  
                atomic.incrementAndGet();  
            }  
            long end1 = System.currentTimeMillis();  
            System.out.println("time elapse:"+(end1 -start1) );  
              
              
        }  

    结果

    time elapse:31
    time elapse:16
    由此不难看出,通过JNI本地的CAS性能远超synchronized关键字

  • 相关阅读:
    hdu 5119 Happy Matt Friends
    hdu 5128 The E-pang Palace
    hdu 5131 Song Jiang's rank list
    hdu 5135 Little Zu Chongzhi's Triangles
    hdu 5137 How Many Maos Does the Guanxi Worth
    hdu 5122 K.Bro Sorting
    Human Gene Functions
    Palindrome(最长公共子序列)
    A Simple problem
    Alignment ( 最长上升(下降)子序列 )
  • 原文地址:https://www.cnblogs.com/android-zcq/p/3183251.html
Copyright © 2011-2022 走看看