zoukankan      html  css  js  c++  java
  • AtomicInteger小小的理解

    这里仅仅是验证多线程环境下,AtomicInteger的安全性。

    通过源码不难发现两点:

    1、value属性是volatile修饰

    2、使用了unsafe的CAS操作

    通过上述两点,实现非阻塞同步(乐观锁),实现线程安全。

    /**
    * 验证在并发情况下,AtomicInteger的线程安全性
    * AtomicInteger并不是通过互斥同步(Syncronized)实现的
    * 其value属性用volatile修饰,保证其可见性(对对象的修改,对其他线程立即可见)
    * 同时,通过 CAS(compare and swap)这一原子操作,保证其多线程安全
    *
    * Atomically increments by one the current value.
    * public final int incrementAndGet() {
        for (;;) {
          int current = get(); // 获取volatile value最新值
          int next = current + 1; // 期望值,也就是本次执行后的值,这里是自增1
          if (compareAndSet(current, next)) // 使用CAS这一原子操作比较current,如果相同,则将next这个新值设置进去;如果current发生变化,则继续循环取值-CAS操作
          return next;
        }
      }
    *
    * @author zhuotao
    *
    */
    public class AtomicIntegerTest {

      private static AtomicInteger atomInt = new AtomicInteger();
      private static final int THREAD_COUNT = 20;

      public static void main(String[] args) {

        Thread[] threads = new Thread[THREAD_COUNT];
        for(int i = 0; i < THREAD_COUNT; i++) {
          threads[i] = new Thread(new Runnable() {
            @Override
            public void run() {
              for(int j = 0; j < 1000; j++) {
                atomInt.incrementAndGet();
              }
            }

          });
          threads[i].start();
        }

        while(Thread.activeCount() > 1) Thread.yield();  // 如果在当前thread group中仍然存在活跃线程,执行yield操作,通知调度器放弃当前使用的procesor
        System.out.println(atomInt.get());

      }

    }

  • 相关阅读:
    【java】一维数组循环位移方阵
    【java】for循环输出数字金字塔
    C++编程tips
    C++中cin.get 和cin.peek 及其相关的用法
    ubuntu增加字符设备驱动程序/ 操作系统课程设计
    C++ Primer 学习笔记/ 处理类型
    C++学习,顶层const
    C++学习笔记/const和指针
    ubuntu16.04增加系统调用(拷贝)
    Java学习笔记#数组 循环遍历
  • 原文地址:https://www.cnblogs.com/aking1988/p/4572220.html
Copyright © 2011-2022 走看看