synchronized,AtomicLong 和 LongAddr

测试 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();

    @SneakyThrows
    public 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));
//-- longAddr
        Thread[] 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));

// ---- synchronized
        Thread[] 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));

    }

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值