Java併發——AtomicInteger類



java.util.concurrent.atomic.AtomicInteger 類提供對底層 int 值的原子操作,這些操作可以原子地讀取和寫入,並且還包含高階原子操作。AtomicInteger 支援對底層 int 變數的原子操作。它具有 get 和 set 方法,其作用類似於對 volatile 變數的讀取和寫入。也就是說,set 操作與隨後對同一變數的任何 get 操作之間存在 happens-before 關係。atomic compareAndSet 方法也具有這些記憶體一致性特性。

AtomicInteger 方法

以下是 AtomicInteger 類中一些重要方法的列表。

序號 方法及描述
1

public int addAndGet(int delta)

原子地將給定值新增到當前值。

2

public boolean compareAndSet(int expect, int update)

如果當前值與預期值相同,則原子地將值設定為給定的更新值。

3

public int decrementAndGet()

原子地將當前值減 1。

4

public double doubleValue()

將指定數字的值作為雙精度浮點數返回。

5

public float floatValue()

將指定數字的值作為單精度浮點數返回。

6

public int get()

獲取當前值。

7

public int getAndAdd(int delta)

原子地將給定值新增到當前值。

8

public int getAndDecrement()

原子地將當前值減 1。

9

public int getAndIncrement()

原子地將當前值加 1。

10

public int getAndSet(int newValue)

原子地設定為給定值並返回舊值。

11

public int incrementAndGet()

原子地將當前值加 1。

12

public int intValue()

將指定數字的值作為整數返回。

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
廣告