current保重的atomic解析
来源:互联网 发布:js初始化 编辑:程序博客网 时间:2024/06/08 14:10
对于current中的automic应用,可以比较如下一段代码,他是线程安全的。通常的++操作会涉及到先get 再add的操作,是两个步骤的操作,所以在多线程操作的时候,会导致计数结果不准确。通常总数会小于我们期望的数值。
而使用atomic类,在底层采用了cas的原子指令:(引用)
CAS通过调用JNI的代码实现的。JNI:Java Native Interface为JAVA本地调用,允许java调用其他语言
而compareAndSwapInt就是借助C来调用CPU底层指令实现的。
下面从分析比较常用的CPU(intel x86)来解释CAS的实现原理。
下面是sun.misc.Unsafe类的compareAndSwapInt()方法的源代码:
public final native boolean compareAndSwapInt(Object o, long offset, int expected, int x);在底层操作的时候,会比较except和current是否一致,如一致,再+x或者-x。这个就是cas的原理。
因此对于上层调用,避免了线程不安全的因素。
如下代码:
package ReentrantLock;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;
public class ReentrantLockClass {
protected SeqAdd seq = new SeqAdd(0);
protected CountDownLatch latch = new CountDownLatch(10000);
protected SeqAutomic seqA = new SeqAutomic();
public void test(){
for(int i = 0;i<10000;i++){
new Thread(){
public void run(){
seq.increase();
seqA.increase();
latch.countDown();
}
}.start();
}
try {
latch.await();
System.out.println(seq.get());
System.out.println(seqA.get());
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String[] args){
new ReentrantLockClass().test();
}
class SeqAdd{
SeqAdd(int count){
this.count = count;
}
private int count;
public int get(){
return count;
}
private void increase(){
count++;
}
private void decrease(){
count--;
}
}
class SeqAutomic{
private AtomicInteger count = new AtomicInteger(0);
public void increase(){
count.getAndIncrement();
}
public void decrease(){
count.getAndDecrement();
}
public int get(){
return count.get();
}
}
}
- current保重的atomic解析
- 写博客的人如何保重龙体?
- 写博客的人如何保重龙体?
- 勤劳的 coder 们注意保重身体...
- atomic与nonatomic解析
- 工作的时候不能太拼 保重身体
- 内核 current宏解析
- 保重身体
- atomic noatomic的作用
- Atomic
- atomic
- Atomic
- current包中countdownlatch解析
- atomic,nonatomic 是干什么的?
- Java Atomic的使用总结
- nonatomic与atomic的区别
- #include <atomic> 引入的错误
- NONATOMIC与ATOMIC的区别
- 轻松学习正则表达式
- 1002. 双栈排序
- selenium web自动化测试工具
- 【独家】加入时间特征的船舶轨迹离线压缩算法——动态Douglas-Peucker算法
- Golden Goose Pas cher slowly
- current保重的atomic解析
- 区块链开发技术路线的思考(二)
- Masonry适配——(1)使用注意事项
- win2012R2打Windows8.1-KB2919355 问题
- Spring项目单元测试
- XML fragments parsed from previous mappers already contains value for
- 第四周项目4-猴子选大王
- 第八周--串--项目四--字符串加密--
- 第八周项目3—将c1字符换成值为c2字符