使用循环 CAS 实现“原子操作”

1、 代码案例: 借助 AtomicInteger 实现线程安全计数器

package multiThread.art;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
/**
 *  使用循环 CAS 实现原子操作
 */
public class CasDemo {
    /**
     *  创建具有给定初始值的新 AtomicInteger
     */
    private AtomicInteger atomicI = new AtomicInteger(0);
    /**
     * 实例私有的属性变量
     */
    private int i = 0;
    public static void main(String[] args) {
          final CasDemo cas = new CasDemo();
          List<Thread> ts = new ArrayList<Thread>();
          long start = System.currentTimeMillis();
          // 创建 100 个线程,并添加到 ts 的集合中
          for( int j = 0 ; j < 100 ; j++){

              Thread t = new Thread(new Runnable() {
                  @Override
                  public void run() {
                        for( int i = 0 ; i < 1000 ; i++){
                            // 执行线程安全的计数器 , 每个线程执行 1000 次
                            cas.safeCount(cas);
                            // 执行非线程安全计数器
                            //cas.unSafeCount();
                        }
                  }
              });
              ts.add(t);
          }

          // 依次启动 ts 集合中的线程
        for( Thread t : ts){
              t.start();
        }

        // 等待所有的线程执行完成
        for( Thread t : ts){
            try {
                t.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("运行结束后:cas.i  的值为" + cas.i);
        System.out.println("运行结束后:计数器 atomicI 的值为 " + cas.atomicI.get());
        System.out.println("运行所消耗的时间:" + (System.currentTimeMillis() - start));
    }

    /**
     *  使用 CAS 实现线程安全计数器
     */
    private void safeCount(final CasDemo cas){
        // 循环 CAS
        for( ; ; ){
            /**
             *  public final int get()
             *  获取当前值
             */
            int i = atomicI.get();
            System.out.println("获取到的值为:"+ i);
            /**
             * public final boolean compareAndSet(int expect,int update)
             * 如果当前值 == 预期值,则以原子的方式将该值设置为给定的更新值
             */
            boolean suc = atomicI.compareAndSet(i,++i);
            System.out.println("更新的结果为:" + suc);
            if( suc ){
                cas.i = atomicI.get();
                break;
            }
        }

    }
    /**
     * 非线程安全计数器
     */
    private void unSafeCount(){
        i++;
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

小达人Fighting

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

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

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

打赏作者

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

抵扣说明:

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

余额充值