atomic提供原子操作的类

atomicInteger 是提供原子操作的Integer的类,我们对修饰的变量的操作可以看做是原子操作,相当于synchronized,假设我们执行i++操作,该操作不是原子操作,多线程多核操作可能会发生并发安全问题,但是用atomicInteger就不会发生并发问题。

atomicInteger和synchronized的性能差异:(程序说话)

import java.util.concurrent.atomic.AtomicInteger;


public class AtomicIntegerTest {

    private int value;
    public AtomicIntegerTest(int value){
        this.value = value;
    }

    public synchronized int increase(){
        return value++;
    }

    public static void main(String args[]){
        long start = System.currentTimeMillis();

        AtomicIntegerTest test = new AtomicIntegerTest(0);
        for( int i=0;i< 10000000;i++){
            test.increase();
        }
        long end = System.currentTimeMillis();
        System.out.println("synchronized time elapse:"+(end -start));

        long start1 = System.currentTimeMillis();

        AtomicInteger atomic = new AtomicInteger(0);

        for( int i=0;i< 10000000;i++){
            atomic.incrementAndGet();
        }
        long end1 = System.currentTimeMillis();
        System.out.println("atomic time elapse:"+(end1 -start1) );

        long start2 = System.currentTimeMillis();
        int a=0;
        for(int i=0;i<10000000;i++){
            a++;
        }
        long end2 = System.currentTimeMillis();
        System.out.println("unsafe time elapse:"+(end2 -start2) );
    }
}

结果:


synchronized time elapse:345
atomic time elapse:178
unsafe time elapse:0

由此得,在考虑安全的情况下,必定会牺牲一定的性能。atomic的运算速度比synchronized快。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值