标签:Thread int 爆料 System 不看 干货 threads Long AtomicLong
测试i++三种方式原子性操作的速度
1:synchronized 2:AtomicLong 3:LongAdder
比较结果:大量多线程并发的情况下LongAdder的速度是最快的,synchronized由最慢转为其次快;少数线程情况下AtomicLong和LongAdder的速度差不多;
public class B { private static long j=0L; private static AtomicLong ato=new AtomicLong(0L); private static LongAdder adder=new LongAdder(); public static void main(String[] args) { Thread[] threads=new Thread[10000]; for (int i = 0; i <threads.length ; i++) { threads[i]=new Thread(()->{ for (int k = 0; k < 100000; k++) { ato.incrementAndGet(); } }); } Long start=System.currentTimeMillis(); for(Thread t :threads) t.start(); for(Thread t :threads) { try { t.join(); } catch (InterruptedException e) { e.printStackTrace(); } } Long end =System.currentTimeMillis(); System.out.println("AtomicLong:"+ato.get() +" AtomicLong共消耗:"+(end-start)+"毫秒"); //================================================== Object o=new Object(); for (int i = 0; i <threads.length ; i++) { threads[i]=new Thread(()->{ for (int k = 0; k < 100000; k++) { synchronized (o) { j++; } } }); } Long start1=System.currentTimeMillis(); for(Thread t :threads) t.start(); for(Thread t :threads) { try { t.join(); } catch (InterruptedException e) { e.printStackTrace(); } } Long end1 =System.currentTimeMillis(); System.out.println("synchronized:"+j +" synchronized共消耗:"+(end1-start1)+"毫秒"); //======================================================== for (int i = 0; i <threads.length ; i++) { threads[i]=new Thread(()->{ for (int k = 0; k < 100000; k++) { adder.increment(); } }); } Long start2=System.currentTimeMillis(); for(Thread t :threads) t.start(); for(Thread t :threads) { try { t.join(); } catch (InterruptedException e) { e.printStackTrace(); } } Long end2 =System.currentTimeMillis(); System.out.println("adder:"+adder.longValue() +" adder共消耗:"+(end2-start2)+"毫秒"); } }
标签:Thread,int,爆料,System,不看,干货,threads,Long,AtomicLong 来源: https://www.cnblogs.com/zhaoyangxuan/p/14890238.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。