AtomicInteger

主要属性
private volatile intvalue;
由volatile修饰,volatile关键字参考:http://www.cnblogs.com/dolphin0520/p/3920373.html 


主要方法

/**
* Atomically sets the value to the given updated value
* if the current value { @code ==} the expected value.
*
* @param expect the expected value
* @param update the new value
* @return { @code true} if successful. False return indicates that
* the actual value was not equal to the expected value.
*/
public final boolean compareAndSet ( int expect , int update ) {
    return unsafe . compareAndSwapInt ( this , valueOffset , expect , update ) ;
}
CAS(Compare And Swap):
现代主流CPU都支持的一种硬件级别的原子操作,比较并交换,操作包含三个操作数:
1.内存位置(V)(对应AtomicInteger类中的value)
2.预期原值(A)(对应 compareAndSet 中的expect)
3.新值(B)(对应 compareAndSet 中的update)

如果内存位置的值与预期原值相匹配,那么处理器会自动将该位置值更新为新值;否则,处理器不作任何操作。

优点:效率高,无锁
理解:
volatile和CAS搭配使用,结合了两者的优点,volatile能让变量在多线程之间实现可见性,
也就是说某个线程更改了内存中的数据之后,其他线程缓存失效重新读取内存数据,利用这一点,其他线程能实时跟进新值,然后用CAS方法,将预期原值(A)与内存中的新值进行比较,再进行下一步操作。从而保证变量的操作的原子性。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值