1.还是看之前的例子,写一个synchronized和Atomic的对比
Atomic是底层基于无锁算法(cas)实现的,synchronized底层是基于有锁算法(aqs)实现的,会走锁升级那块规则流程,在并发竞争激烈的情况下肯定会升级为重量锁的,所以用Atomic的话效率会高很多。
public class AtomicSample {static int sum = 0;static AtomicInteger atomicIntegerSum = new AtomicInteger(0);static int threadCount = 10;public static void main(String[] args) throws InterruptedException {synchronizedTest();AtomicTest();}public static void synchronizedTest() throws InterruptedException {for(int i = 0;i<threadCount;i++){new Thread(()->{//普通的做法是加synchronized,但其实是很影响性能,这里可以用Atomic来实现synchronized (AutoCloseable.class){for(int j=0;j<1000;j++){sum++;}}}).start();}Thread.sleep(3000);System.out.println(sum);}public static void AtomicTest() throws InterruptedException {for(int i = 0;i<threadCount;i++){new Thread(()->{//用Atomic来实现for(int j=0;j<1000;j++){atomicIntegerSum.getAndIncrement();}}).start();}Thread.sleep(3000);System.out.println(atomicIntegerSum.get());}}
2.我们再看看getAndIncrement的方法调用:
.
由此可见,AtomicInteger.incrementAndGet的实现用了乐观锁技术,调用了类sun.misc.Unsafe库里面的 CAS算法,用CPU指令来实现无锁自增。所以,AtomicInteger.incrementAndGet的自增比用synchronized的锁效率倍增。
