主要属性
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)与内存中的新值进行比较,再进行下一步操作。从而保证变量的操作的原子性。
|