Java並行AtomicBoolean類


java.util.concurrent.atomic.AtomicBoolean類提供了可以原子讀取和寫入的底層布林值的操作,並且還包含高階原子操作。 AtomicBoolean支援基礎布林變數上的原子操作。 它具有獲取和設定方法,如在volatile變數上的讀取和寫入。 也就是說,一個集合與同一變數上的任何後續get相關聯。 原子compareAndSet方法也具有這些記憶體一致性功能。

AtomicBoolean類中的方法

以下是AtomicBoolean類中可用的重要方法的列表。

序號 方法 描述
1 public boolean compareAndSet(boolean expect, boolean update) 如果當前值==期望值,則將該值原子設定為給定的更新值。
2 public boolean get() 返回當前值。
3 public boolean getAndSet(boolean newValue) 將原子設定為給定值並返回上一個值。
4 public void lazySet(boolean newValue) 最終設定為給定值。
5 public void set(boolean newValue) 無條件地設定為給定的值。
6 public String toString() 返回當前值的String表示形式。
7 public boolean weakCompareAndSet(boolean expect, boolean update) 如果當前值==期望值,則將該值原子設定為給定的更新值。

範例

以下TestThread程式顯示了基於執行緒的環境中AtomicBoolean變數的使用。

import java.util.concurrent.atomic.AtomicBoolean;

public class TestThread {

   public static void main(final String[] arguments) throws InterruptedException {
      final AtomicBoolean atomicBoolean = new AtomicBoolean(false);
      new Thread("Thread 1") {
         public void run() {
            while(true){
               System.out.println(Thread.currentThread().getName() 
                  +" Waiting for Thread 2 to set Atomic variable to true. Current value is "
                  + atomicBoolean.get());
               if(atomicBoolean.compareAndSet(true, false)) {
                  System.out.println("Done!");
                  break;
               }
            }};
      }.start();

      new Thread("Thread 2") {
         public void run() {
            System.out.println(Thread.currentThread().getName() + ", Atomic Variable: " +atomicBoolean.get()); 
            System.out.println(Thread.currentThread().getName() +" is setting the variable to true ");
            atomicBoolean.set(true);
            System.out.println(Thread.currentThread().getName() + ", Atomic Variable: " +atomicBoolean.get()); 
         };
      }.start();
   }  
}

這將產生以下結果 -

Thread 1 Waiting for Thread 2 to set Atomic variable to true. Current value is false
Thread 1 Waiting for Thread 2 to set Atomic variable to true. Current value is false
Thread 1 Waiting for Thread 2 to set Atomic variable to true. Current value is false
Thread 2, Atomic Variable: false
Thread 1 Waiting for Thread 2 to set Atomic variable to true. Current value is false
Thread 2 is setting the variable to true
Thread 2, Atomic Variable: true
Thread 1 Waiting for Thread 2 to set Atomic variable to true. Current value is false
Done!