當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Java AtomicLongArray compareAndSet()用法及代碼示例


Java.util.concurrent.atomic.AtomicLongArray.compareAndSet()是Java中的一種內置方法,如果當前值等於預期值,則該方法原子地將元素設置在給定的更新值。此方法將索引值,期望值和更新值作為參數,並返回一個布爾值,說明該值是否已更新。

用法:

public final boolean compareAndSet(int i, long expect, long update)



參數:該函數接受三個參數:

  • i:要進行操作的索引。
  • expect:要檢查的期望值是否等於當前值。
  • update:要更新的值。

返回值:該函數返回一個布爾值,說明該值是否已更新。如果成功,則返回true,否則返回false,指示當前值不等於期望值。

以下示例程序旨在說明上述方法:
示例1:

// Java program that demonstrates 
// the compareAndSet() function 
  
import java.util.concurrent.atomic.AtomicLongArray; 
  
public class GFG { 
    public static void main(String args[]) 
    { 
        // Initializing an array 
        long a[] = { 1, 2, 3, 4, 5 }; 
  
        // Initializing an AtomicLongArray with array a 
        AtomicLongArray arr = new AtomicLongArray(a); 
  
        // Displaying the AtomicLongArray 
        System.out.println("The array : " + arr); 
  
        // Index where operation is performed 
        int idx = 3; 
  
        // Value to expect at idx 
        long expect = 4; 
  
        // Value to update if current value 
        // is equal to expected value 
        long update = 40; 
  
        // Updating the value at idx 
        // applying compareAndSet 
        arr.compareAndSet(idx, expect, update); 
  
        // Displaying the AtomicLongArray 
        System.out.println("The array after update : "
                           + arr); 
    } 
}
輸出:
The array : [1, 2, 3, 4, 5]
The array after update : [1, 2, 3, 40, 5]

示例2:

// Java program that demonstrates 
// the compareAndSet() function 
  
import java.util.concurrent.atomic.AtomicLongArray; 
  
public class GFG { 
    public static void main(String args[]) 
    { 
        // Initializing an array 
        long a[] = { 1, 2, 3, 4, 5 }; 
  
        // Initializing an AtomicLongArray with array a 
        AtomicLongArray arr = new AtomicLongArray(a); 
  
        // Displaying the AtomicLongArray 
        System.out.println("The array : " + arr); 
  
        // Index where operation is performed 
        int idx = 3; 
  
        // Value to expect at idx 
        long expect = 40; 
  
        // Value to update if current value 
        // is equal to expected value 
        long update = 4; 
  
        // Updating the value at 
        // idx applying compareAndSet 
        arr.compareAndSet(idx, expect, update); 
  
        // Displaying the AtomicLongArray 
        System.out.println("The array after update : "
                           + arr); 
    } 
}
輸出:
The array : [1, 2, 3, 4, 5]
The array after update : [1, 2, 3, 4, 5]

參考:
https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/atomic/AtomicLongArray.html#compareAndSet-int-long-long-



相關用法


注:本文由純淨天空篩選整理自rupesh_rao大神的英文原創作品 AtomicLongArray compareAndSet() method in Java with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。