爆料干货,不看后悔

测试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)+"毫秒");
    }
}

 

上一篇:六十五、性能测试


下一篇:多次start一个线程会怎么样