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快。