Java并发AtomicInteger类


java.util.concurrent.atomic.AtomicInteger类提供对基本int值的操作,该值可以以原子方式读取和写入,并且还包含高级的原子操作。AtomicInteger支持底层int变量的原子操作。它具有读取和写入易失性变量的方法。也就是说,一个集合与之后的任何一个变量之间都有一个前后关系。原子compareAndSet方法也具有这些内存一致性功能。

AtomicInteger方法

以下是AtomicInteger类中可用的重要方法的列表。

Sr.No. 方法和描述
1 public int addAndGet(int delta) 原子上将给定值添加到当前值。
2 public boolean compareAndSet(int expect,int update) 如果当前值与期望值相同,则按原子值将该值设置为给定的更新值。
3 public int decrementAndGet() 原子减少一个当前值。
4 public double doubleValue() 以double形式返回指定数字的值。
5 public float floatValue() 以浮点形式返回指定数字的值。
6 public int get() 获取当前值。
7 public int getAndAdd(int delta) Atomiclly将给定值添加到当前值。
8 public int getAndDecrement() 原子减少一个当前值。
9 public int getAndIncrement() 原子上增加一个当前值。
10 public int getAndSet(int newValue) 原子级设置为给定值并返回旧值。
11 public int incrementAndGet() 原子上增加一个当前值。
12 public int intValue() 以int形式返回指定数字的值。
13 public void lazySet(int newValue) 最终设置为给定值。
14 public long longValue() 以长整数形式返回指定数字的值。
15 public void set(int newValue) 设置为给定值。
16 public String toString() 返回当前值的字符串表示形式。
17 public boolean weakCompareAndSet(int expect,int update) 如果当前值与期望值相同,则按原子值将该值设置为给定的更新值。

以下TestThread程序显示基于线程的环境中不安全的计数器实现。

public class TestThread {

   static class Counter {
      private int c = 0;

      public void increment() {
         c++;
      }

      public int value() {
         return c;
      }
   }

   public static void main(final String[] arguments) throws InterruptedException {
      final Counter counter = new Counter();

      //1000 threads
      for(int i = 0; i < 1000 ; i++) {

         new Thread(new Runnable() {

            public void run() {
               counter.increment();
            }
         }).start();
      }  
      Thread.sleep(6000);
      System.out.println("Final number (should be 1000): " + counter.value());
   }  
}

根据计算机的速度和线程交错,这可能会产生以下结果。

输出

Final number (should be 1000): 1000

以下TestThread程序在基于线程的环境中使用AtomicInteger显示计数器的安全实现。

import java.util.concurrent.atomic.AtomicInteger;

public class TestThread {

   static class Counter {
      private AtomicInteger c = new AtomicInteger(0);

      public void increment() {
         c.getAndIncrement();
      }

      public int value() {
         return c.get();
      }
   }

   public static void main(final String[] arguments) throws InterruptedException {
      final Counter counter = new Counter();

      //1000 threads
      for(int i = 0; i < 1000 ; i++) {

         new Thread(new Runnable() {
            public void run() {
               counter.increment();
            }
         }).start();
      }  
      Thread.sleep(6000);
      System.out.println("Final number (should be 1000): " + counter.value());
   }
}

这将产生以下结果。

输出

Final number (should be 1000): 1000