Atomic包中AtomicInteger原子类型学习

AtomicInteger,一个提供原子操作的Integer的类。在Java语言中,++i和i++操作并不是线程安全的,在使用的时候,不可避免的会用到synchronized关键字。
来看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)

... ...

getAndSet:设置为新值,返回设置之前的值。此方法为原子性操作,即保证在得到当前值与设置新值之间,没有任何其他更新操作。

01.public final int getAndSet(int newValue) {
02. for (;;) {
03. int current = get();
04. if (compareAndSet(current, newValue))
05. return current;
06. }
07. }


getAndIncrement:当前值加一,返回自增前的值。此方法为原子性操作,即保证在得到当前值与自增之间,没有任何其他更新操作。举个例子,假如是value++,两个线程同时调用此函数,两个线程都取到了当前值100,然后都基于100加一,最后得到101,miss掉了一次自增。采用compareAndSet,两个线程同时取到当前值100,线程一成功调用compareAndSet,当前值变为101,返回;线程二调用compareAndSet失败,回到循环头,重新取得一个新的当前值101,接着成功调用comareAndSet,更新当前值为102,返回


01.public final int getAndIncrement() {
02. for (;;) {
03. int current = get();
04. int next = current + 1;
05. if (compareAndSet(current, next))
06. return current;
07. }
08.nbsp;}


compareAndSet:如果当前值与期望值(第一个参数)相等,则设置为新值(第二个参数),设置成功返回true。


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


compareAndSet:如果当前值与期望值相等,更新对象的一个整数属性(field)为给定的值。更新则返回true,否则为false。此方法为原子性操作,而且是native方法。


01.public native boolean compareAndSwapInt(Object obj, long offset,
02. int expect, int update);
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值