原子更新基本类型类:

  1. AtomicBoolean:原子更新布尔类型。
  2. AtomicInteger:原子更新整型。
  3. AtomicLong:原子更新长整型。

核心API:

  • int addAndGet(int delta):以原子方式将输入的数值与实例中的值(AtomicInteger里的value)相加,并返回结果。

    1. int res = 0;
    2. boolean flag = false;
    3. AtomicInteger aInteger = new AtomicInteger(1);
    4. res = aInteger.addAndGet(5);
    5. System.out.println("Res:" + res); // 6
    6. System.out.println("AtomicInteger:" + aInteger); // 6
  • boolean compareAndSet(int expect,int update):如果输入的数值等于预期值,则以原子方式将该值设置为输入的值。

    1. flag = aInteger.compareAndSet(6, 10);
    2. System.out.println("Flag:" + flag); // true
  • int getAndIncrement():以原子方式将当前值加1,注意,这里返回的是自增前的值。

    1. res = aInteger.getAndIncrement(); // 此时 aInteger 为10
    2. System.out.println("Res:" + res); // 10
    3. System.out.println("AtomicInteger:" + aInteger); // 11
  • int getAndSet(int newValue):以原子方式设置为newValue的值,并返回旧值。

    1. res = aInteger.getAndSet(5);
    2. System.out.println("After getAndSet");
    3. System.out.println("Res:" + res); // 11 (原来的旧值)
    4. System.out.println("AtomicInteger:" + aInteger);// 5
  • void lazySet(int newValue):最终会设置成newValue,使用lazySet设置值后,可能导致其他线程在之后的一小段时间内还是可以读到旧的值。

    2、原子更新数组

    通过原子的方式更新数组里的某个元素,Atomic包提供了以下4个类。

  • AtomicIntegerArray:原子更新整型数组里的元素。

  • AtomicLongArray:原子更新长整型数组里的元素。
  • AtomicReferenceArray:原子更新引用类型数组里的元素。

核心 API:

  • int addAndGet(int i,int delta):以原子方式将输入值与数组中索引i的元素相加。
  • boolean compareAndSet(int i,int expect,int update):如果当前值等于预期值,则以原子方式将数组位置i的元素设置成update值。

    1. static int[] value = new int[] { 1, 2 };
    2. static AtomicIntegerArray ai = new AtomicIntegerArray(value);
    3. System.out.println(ai.getAndSet(0, 3)); // 1
    4. System.out.println(ai.get(0)); // 3
    5. System.out.println(value[0]); // 1

    3、原子更新引用类型

    原子更新基本类型的AtomicInteger,只能更新一个变量,如果要原子更新多个变量,就需要使用这个原子更新引用类型提供的类。Atomic包提供了以下3个类。

  • AtomicReference:原子更新引用类型。

  • AtomicReferenceFieldUpdater:原子更新引用类型里的字段。
  • AtomicMarkableReference:原子更新带有标记位的引用类型。可以原子更新一个布尔类型的标记位和引用类型。构造方法是AtomicMarkableReference(V initialRef,boolean initialMark)。
    1. static AtomicReference<User> atomicUserRef = new AtomicReference<>();
    2. User user = new User("Conon", 15);atomicUserRef.set(user);
    3. User updateUser = new User("Shaw", 18);
    4. atomicUserRef.compareAndSet(user, updateUser);
    5. System.out.println(atomicUserRef.get().getName());
    6. System.out.println(atomicUserRef.get().getOld());

    4、原子更新字段类

    如果需要原子地更新某个类里的某个字段时,就需要使用原子更新字段类。Atomic 包提供了以下 3 个进行原子字段更新。