原子类AtomicInteger

介绍

AtomicInteger是一个提供原子操作的Integer类,通过线程安全的方式操作加减
CAS的全程为Compare-And-Swap,它是一条CPU并发原语
CAS的核心是Unsafe类,Unsafe的native方法可以直接访问内存
原子类AtomicInteger_第1张图片
原子类AtomicInteger_第2张图片

实现原理

AtomicInteger简单来说就是一个能进行原子操作的Integer,这样在多线程操作下对AtomicInteger的操作是原子操作的,操作后的值对所有线程都是立即可见的。
简单来说其实现就是使用的volatile变量value和sun.misc.Unsafe提供的CAS操作完成的,volatile变量value就表明任意一个线程对value的操作都是对其他线程可见的,并且对于value的修改使用Unsafe提供的方法实现线程不阻塞来完成对value值的修改等操作。

AtomicInteger的变量值:

private volatile int value;

get和set操作就是直接赋值给value

 /**
 * Gets the current value.
 * @return the current value
 */
public final int get() {
    return value;
}

/**
 * Sets to the given value.
 * @param newValue the new value
 */
public final void set(int newValue) {
    value = newValue;
}

加加和减减操作就是使用Unsafe提供的方法完成CAS操作(乐观锁)

/**
  * Atomically increments by one the current value.
  * @return the updated value
  */
 public final int incrementAndGet() {
     return unsafe.getAndAddInt(this, valueOffset, 1) + 1;
 }

 /**
  * Atomically decrements by one the current value.
  * @return the updated value
  */
 public final int decrementAndGet() {
     return unsafe.getAndAddInt(this, valueOffset, -1) - 1;
 }

代码测试

/**
 * @author yanyugang
 * @description AtomicInteger的使用
 * @date 2019/9/7 11:34
 */
public class AtomicIntegerTest {
    private static final AtomicInteger num = new AtomicInteger(0);
    // 设置200条订单生成一个文件
    private static final AtomicInteger total = new AtomicInteger(2);

    public static void main(String[] args) {
        // 比较相等
        if (num.get() == total.get()) {
            System.out.println("equal");
        }
        // 加一
        num.addAndGet(1);
        // 加一
        num.addAndGet(1);
        System.out.println(num);
        System.out.println(total);
        if (num.get() == total.get()) {
            System.out.println("equal");
        }
        // 置0
        num.getAndSet(0);
        total.getAndSet(0);
        System.out.println(num);
        System.out.println(total);
    }
}

使用场景

AtomicInteger提供原子操作来进行Integer的使用,因此十分适合高并发情况下的使用。

总结

简单来说AtomicInteger的实现原理就是通过一个volatile的变量value以及Unsafe类提供的CAS操作来完成的。
AtomicInteger是在使用非阻塞算法实现并发控制,在一些高并发程序中非常适合,但并不能每一种场景都适合,不同场景要使用使用不同的数值类。


参考文档:

  1. https://blog.csdn.net/qq924862077/article/details/68943417

你可能感兴趣的:(并发编程,AtomicInteger,CAS乐观锁,JAVA)