您现在的位置是:首页
>
volatile原理cas JAVA高级:多核线程-volatile原理与技巧[3]
JAVA高级:多核线程-volatile原理与技巧[3] CAS 原理 我认为位置V 应该包含值A 如果包含该值 则将B 放到这个位置 否则 不要更改该位置 只告诉我这个位置现在的值即可 CAS使用示
JAVA高级:多核线程-volatile原理与技巧[3]
CAS 原理
我认为位置V 应该包含值A 如果包含该值 则将B 放到这个位置 否则 不要更改该位置 只告诉我这个位置现在的值即可
CAS使用示例(jdk 并发包 AtomicInteger类分析
/*** Atomically sets to the given value and returns the old value ** @param newValue the new value* @return the previous value*/ public final int getAndSet(int newValue) {for (;;) {int current = get();if (pareAndSet(current newValue))return current;}}public final boolean pareAndSet(int expect int update) {return unsafe pareAndSwapInt(this valueOffset expect update);}
这个方法是 AtomicInteger类的常用方法 作用是 将变量设置为指定值 并返回设置前的值
它利用了cpu原语pareAndSet来保障值的唯一性
另 AtomicInteger类中 其他的实用方法 也是基于同样的实现方式
比如 getAndIncrement getAndDecrement getAndAdd等等
![volatile原理cas JAVA高级:多核线程-volatile原理与技巧[3]](http://img.zhputi.com/uploads/3e36/3e363b1271e60880b37376f64c9ce189104908.jpg)
lishixinzhi/Article/program/Java/gj/201311/27719
很赞哦! (1052)