并发编程——AtomicInterger与i++

一、对比

在高并发的情况下整形数值自增并不是线程安全的,在双11抢购是发统计某网页浏览量,这时可以用到原子更新整形AtomicInteger。

先看个例子:

public class TestAtomicInteger {
    static int a=0;

    public static void main(String args[]){
        CountDownLatch countDown=new CountDownLatch(2);
        AtomicInteger atomicInteger=new AtomicInteger();

        Thread t1=new Thread(new Runnable() {
            @Override
            public void run() {
                for(int i=0;i<10000000;i++){
                    atomicInteger.incrementAndGet();
                    a++;
                }
                countDown.countDown();
            }
        });
        t1.start();

        Thread t2=new Thread(new Runnable(){
            @Override
            public void run() {
                for(int i=0;i<10000000;i++){
                    atomicInteger.incrementAndGet();
                    a++;
                }
                countDown.countDown();
            }
        });
        t2.start();

        try {
            countDown.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("a= "+a);
        System.out.println("atomicinteger= "+atomicInteger.get());
    }
}

运行结果:

代码中CountDownLatch用于等待t1,t2线程结束,每个线程结束需要手动减,利用方法countDown()。从运行结果可以看到a++所得到的结果并不是我们期待的值。在高并发情景下其并不是安全的。

二、扩展

下面给出方法说明,源码在java.util.concurrent.atomic包下,感兴趣可以自行学习

Modifier and TypeMethod and Description
intaccumulateAndGet(int x, IntBinaryOperator accumulatorFunction)

使用将给定函数应用于当前值和给定值的结果原子更新当前值,返回更新后的值。

intaddAndGet(int delta)

将给定的值原子地添加到当前值。

booleancompareAndSet(int expect, int update)

如果当前值 ==为预期值,则将该值原子设置为给定的更新值。

intdecrementAndGet()

原子减1当前值。

doubledoubleValue()

返回此值 AtomicInteger为 double一个宽元转换后。

floatfloatValue()

返回此值 AtomicInteger为 float一个宽元转换后。

intget()

获取当前值。

intgetAndAccumulate(int x, IntBinaryOperator accumulatorFunction)

使用给定函数应用给当前值和给定值的结果原子更新当前值,返回上一个值。

intgetAndAdd(int delta)

将给定的值原子地添加到当前值。

intgetAndDecrement()

原子减1当前值。

intgetAndIncrement()

原子上增加一个当前值。

intgetAndSet(int newValue)

将原子设置为给定值并返回旧值。

intgetAndUpdate(IntUnaryOperator updateFunction)

用应用给定函数的结果原子更新当前值,返回上一个值。

intincrementAndGet()

原子上增加一个当前值。

intintValue()

将 AtomicInteger的值作为 int 。

voidlazySet(int newValue)

最终设定为给定值。

longlongValue()

返回此值 AtomicInteger为 long一个宽元转换后。

voidset(int newValue)

设置为给定值。

StringtoString()

返回当前值的String表示形式。

intupdateAndGet(IntUnaryOperator updateFunction)

使用给定函数的结果原子更新当前值,返回更新的值。

booleanweakCompareAndSet(int expect, int update)

如果当前值 ==为预期值,则将值设置为给定更新值。

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值