手动实现CAS 思想之 AtomicInteger 自增原理(十一)

1、手动实现CAS 思想之自增原理:

public class HalfAtomicInt {
    private static  AtomicInteger atomicI = new AtomicInteger(0);

    /*CAS递增方法实现*/
    public void increament() {
        for (;;) {//死循环操作,直到成功为止
            int i = getCount();//获取当前的值
            boolean suc = compareAndSet(i, ++i);//比较并交换方法
            if (suc) {
                break;
            }
        }
    }
    
    public int getCount() {
    	return atomicI.get();
    }

    public boolean compareAndSet(int oldValue,int newValue){
        return atomicI.compareAndSet(oldValue,newValue);
    }

    public static void main(String[] args) throws InterruptedException {
        long startTime = System.currentTimeMillis();
        HalfAtomicInt halfAtomicInt = new HalfAtomicInt();
        for(int i=0;i<10;i++){//循环十次,开十个线程
            new Thread(new Runnable() {
                @Override
                public void run() {//每个线程循环1000次
                    for(int i=0;i<1000;i++){
                        halfAtomicInt.increament();
                        atomicI.incrementAndGet();//CAS自有的自增操作,只能一次加一。
                    }
                }
            }).start();
        }
        Thread.sleep(20);
        System.out.println("调用incrementAndGet方法自增后:"+atomicI.get()+";耗时:"+(System.currentTimeMillis()-startTime));
        System.out.println("调用iincreament方法自增后:"+halfAtomicInt.getCount()+";耗时:"+(System.currentTimeMillis()-startTime));
    }

}

执行结果:

此实例demo在项目中经常用到,只需换一种业务方式,是自增还是其他规律赋值。其主要API有:

public final int get() //获取当前的值
public final int getAndSet(int newValue)//获取当前的值,并设置新的值
public final int getAndIncrement()//获取当前的值,并自增
public final int getAndDecrement() //获取当前的值,并自减
public final int getAndAdd(int delta) //获取当前的值,并加上预期的值
public final int incrementAndGet() //获取自增后的值
public final int decrementAndGet()//获取自减后的值

大家可以多测试使用一下,

2、当然也可以用synchronized 内置锁实现:

private static int i=0;
//此方式效率比较低
public  synchronized static int countSum(){
        i++;
        return i;
    }

分享到处结束,下篇我们分析AQS原理及使用,敬请期待!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

寅灯

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值