atomic提供原子操作的类
2016-02-05 12:04
627 查看
atomicInteger 是提供原子操作的Integer的类,我们对修饰的变量的操作可以看做是原子操作,相当于synchronized,假设我们执行i++操作,该操作不是原子操作,多线程多核操作可能会发生并发安全问题,但是用atomicInteger就不会发生并发问题。
atomicInteger和synchronized的性能差异:(程序说话)
结果:
synchronized time elapse:345
atomic time elapse:178
unsafe time elapse:0
由此得,在考虑安全的情况下,必定会牺牲一定的性能。atomic的运算速度比synchronized快。
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快。
相关文章推荐
- java对世界各个时区(TimeZone)的通用转换处理方法(转载)
- java-注解annotation
- java-模拟tomcat服务器
- java-用HttpURLConnection发送Http请求.
- java-WEB中的监听器Lisener
- Android IPC进程间通讯机制
- Android Native 绘图方法
- Android java 与 javascript互访(相互调用)的方法例子
- 介绍一款信息管理系统的开源框架---jeecg
- 聚类算法之kmeans算法java版本
- java实现 PageRank算法
- PropertyChangeListener简单理解
- c++11 + SDL2 + ffmpeg +OpenAL + java = Android播放器
- 插入排序
- 冒泡排序
- 堆排序
- 快速排序
- 二叉查找树