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]
相关用法
- Java AtomicLong compareAndSet()用法及代码示例
- Java AtomicReference compareAndSet()用法及代码示例
- Java AtomicReferenceArray compareAndSet()用法及代码示例
- Java AtomicBoolean compareAndSet()用法及代码示例
- Java AtomicIntegerArray compareAndSet()用法及代码示例
- Java AtomicInteger compareAndSet()用法及代码示例
- Java AtomicLongArray set()用法及代码示例
- Java AtomicLongArray get()用法及代码示例
- Java AtomicLongArray getAndDecrement()用法及代码示例
- Java AtomicLongArray incrementAndGet()用法及代码示例
- Java AtomicLongArray addAndGet()用法及代码示例
- Java AtomicLongArray accumulateAndGet()用法及代码示例
- Java AtomicLongArray decrementAndGet()用法及代码示例
- Java AtomicLongArray getAndUpdate()用法及代码示例
- Java AtomicLongArray updateAndGet()用法及代码示例
注:本文由纯净天空筛选整理自rupesh_rao大神的英文原创作品 AtomicLongArray compareAndSet() method in Java with Examples。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。