您的位置:首页 > 其它

AtomicInteger 学习

2017-04-19 10:20 363 查看
AtomicInteger,一个提供原子操作的Integer的类。在Java语言中,为了保证一个数字的更新只能被一个类获取,在使用的时候,不可避免的会用到synchronized关键字。而AtomicInteger则通过一种线程安全的加减操作接口。该类的类中方法无法被重载,都添加了final关键字

//获取当前的值
public final int get()
//取当前的值,并设置新的值
 public final int getAndSet(int newValue)
//获取当前的值,并自增
 public final int getAndIncrement()
//获取当前的值,并自减
public final int getAndDecrement()
//获取当前的值,并加上预期的值
public final int getAndAdd(int delta)
代码学习:
考究他们的性能

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关键字
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息