当前位置: 代码迷 >> 综合 >> synchronized,AtomicLong 和 LongAddr
  详细解决方案

synchronized,AtomicLong 和 LongAddr

热度:59   发布时间:2024-01-20 17:46:28.0

测试 synchronized(升级,申请总线锁) 对Long 做++操作 和 AtomicLong(CAS实现)  LongAddr(分段+CAS实现)

先说结论

高并发情况下,LongAddr 优于 Atomic 优于 Synchronized

public class AtomicLearn {private static long count;private static AtomicLong count1=new AtomicLong(0);private static LongAdder count2=new LongAdder();@SneakyThrowspublic static void main(String[] args) {Thread[] threads=new Thread[1000];for(int i=0;i< threads.length;i++){threads[i]=new Thread(()->{for(int k=0;k<100000;k++){count1.getAndIncrement();}});}long start =System.currentTimeMillis();for (Thread t:threads) t.start();for (Thread t:threads) t.join();System.out.println("Atomic count1="+count1+" 用时:"+(System.currentTimeMillis()-start));
//-- longAddrThread[] threads2=new Thread[1000];for(int i=0;i< threads2.length;i++){threads2[i]=new Thread(()->{for(int k=0;k<100000;k++){count2.increment();}});}long start2 =System.currentTimeMillis();for(Thread t:threads2) t.start();for(Thread t:threads2) t.join();System.out.println("LongAddr count2="+count2+" 用时:"+(System.currentTimeMillis()-start2));// ---- synchronizedThread[] threads0=new Thread[1000];for(int i=0;i< threads0.length;i++){threads0[i]=new Thread(()->{for(int k=0;k<100000;k++){synchronized(AtomicLearn.class){count++;}}});}long start0 =System.currentTimeMillis();for(Thread t:threads0) t.start();for(Thread t:threads0) t.join();System.out.println("synchronized count1="+count+" 用时:"+(System.currentTimeMillis()-start0));}}

 

  相关解决方案