您的位置:首页 > 编程语言 > Java开发

atomic提供原子操作的类

2016-02-05 12:04 627 查看
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快。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java