atomic提供原子操作的类
来源:互联网 发布:px4飞控源码 百度云 编辑:程序博客网 时间:2024/05/16 09:56
atomicInteger 是提供原子操作的Integer的类,我们对修饰的变量的操作可以看做是原子操作,相当于synchronized,假设我们执行i++操作,该操作不是原子操作,多线程多核操作可能会发生并发安全问题,但是用atomicInteger就不会发生并发问题。
atomicInteger和synchronized的性能差异:(程序说话)
import java.util.concurrent.atomic.AtomicInteger;public class AtomicIntegerTest { private int value; public AtomicIntegerTest(int value){ this.value = value; } public synchronized int increase(){ return value++; } public static void main(String args[]){ long start = System.currentTimeMillis(); AtomicIntegerTest test = new AtomicIntegerTest(0); for( int i=0;i< 10000000;i++){ test.increase(); } long end = System.currentTimeMillis(); System.out.println("synchronized time elapse:"+(end -start)); long start1 = System.currentTimeMillis(); AtomicInteger atomic = new AtomicInteger(0); for( int i=0;i< 10000000;i++){ atomic.incrementAndGet(); } long end1 = System.currentTimeMillis(); System.out.println("atomic time elapse:"+(end1 -start1) ); long start2 = System.currentTimeMillis(); int a=0; for(int i=0;i<10000000;i++){ a++; } long end2 = System.currentTimeMillis(); System.out.println("unsafe time elapse:"+(end2 -start2) ); }}
结果:
synchronized time elapse:345
atomic time elapse:178
unsafe time elapse:0
由此得,在考虑安全的情况下,必定会牺牲一定的性能。atomic的运算速度比synchronized快。
0 0
- atomic提供原子操作的类
- Concurrent——Atomic原子操作类
- 原子操作(Atomic)
- 原子操作atomic
- 原子操作(atomic operation)
- atomic 原子操作练习
- sync/atomic - 原子操作
- 原子操作(atomic operation)
- CUDA atomic原子操作
- CUDA atomic原子操作
- GCC 提供的原子操作
- GCC 提供的原子操作
- GCC 提供的原子操作
- GCC 提供的原子操作
- GCC 提供的原子操作
- gcc提供的原子操作
- GCC 提供的原子操作
- GCC 提供的原子操作
- JSP的结构和生命周期
- python机器学习包mlxtend的安装和配置
- 数组中只出现一次的数字
- PAT1002.写出这个数
- 快速掌握Lua 5.3 —— 环境
- atomic提供原子操作的类
- hdu 2078
- 一个资深iOS开发者对于React Native的看法
- Mongo中上传下载图片
- web.xml配置详解
- 关于Struts2中的No result defined for action and result input错误
- 二手吧软件学习build.xml
- 设计一个二次方程计算器
- LIMIT