java.util.concurrent.atomic.AtomicInteger.weakCompareAndSet()是Java中的一种内置方法,如果当前值等于参数给定的期望值,则将值设置为参数中的传递值。该函数返回一个布尔值,该布尔值使我们了解更新是否完成。
用法:
public final boolean weakCompareAndSet(int expect, int val)
参数:该函数接受两个强制性参数,如下所述:
- expect:指定原子对象应为的值。
- val:如果原子整数等于期望值,则指定要更新的值。
返回值:该函数返回一个布尔值,成功则返回true,否则返回false。
以下程序演示了该函数:
示例1:
// Java program that demonstrates
// the weakCompareAndSet() function
import java.util.concurrent.atomic.AtomicInteger;
public class GFG {
public static void main(String args[])
{
// Initially value as 0
AtomicInteger val
= new AtomicInteger(0);
// Prints the updated value
System.out.println("Previous value: "
+ val);
// Checks if previous value was 0
// and then updates it
boolean res
= val.weakCompareAndSet(0, 6);
// Checks if the value was updated.
if (res)
System.out.println("The value was "
+ "updated and it is "
+ val);
else
System.out.println("The value was "
+ "not updated");
}
}
输出:
Previous value: 0 The value was updated and it is 6
示例2:
// Java program that demonstrates
// the weakCompareAndSet() function
import java.util.concurrent.atomic.AtomicInteger;
public class GFG {
public static void main(String args[])
{
// Initially value as 0
AtomicInteger val
= new AtomicInteger(0);
// Prints the updated value
System.out.println("Previous value: "
+ val);
// Checks if previous value was 0
// and then updates it
boolean res
= val.weakCompareAndSet(10, 6);
// Checks if the value was updated.
if (res)
System.out.println("The value was "
+ "updated and it is "
+ val);
else
System.out.println("The value was "
+ "not updated");
}
}
输出:
Previous value: 0 The value was not updated
相关用法
- Java AtomicReference weakCompareAndSet()用法及代码示例
- Java AtomicLong weakCompareAndSet()用法及代码示例
- Java AtomicReferenceArray weakCompareAndSet()用法及代码示例
- Java AtomicInteger set()用法及代码示例
- Java AtomicInteger get()用法及代码示例
- Java AtomicInteger lazySet()用法及代码示例
- Java AtomicInteger incrementAndGet()用法及代码示例
- Java AtomicInteger intValue()用法及代码示例
- Java AtomicInteger doubleValue()用法及代码示例
- Java AtomicInteger getAndDecrement()用法及代码示例
- Java AtomicInteger toString()用法及代码示例
- Java AtomicInteger updateAndGet()用法及代码示例
- Java AtomicInteger getAndAccumulate()用法及代码示例
- Java AtomicInteger floatValue()用法及代码示例
- Java AtomicInteger longValue()用法及代码示例
注:本文由纯净天空筛选整理自gopaldave大神的英文原创作品 AtomicInteger weakCompareAndSet() method in Java with examples。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。