Java中的AtomicInteger compareAndSet()方法及示例

Java中的AtomicInteger compareAndSet()方法及示例

java.util.concurrent.atomic.AtomicInteger.compareAndSet() 是java中的一个内置方法,如果当前值与参数中传递的预期值相等,则将该值设置为参数中传递的值。该函数返回一个布尔值,让我们知道是否进行了更新。

语法

public final boolean compareAndSet(int expect, int val)

参数: 该函数接受两个强制性参数,如下所述。

  • expect: 它指定了原子对象应该有的值。
  • val: 它指定了在原子整数等于期望值时要更新的值。

返回值: 该函数返回一个布尔值,成功时返回真,否则返回假。

下面的程序演示了这个函数。

程序1 :

// Java Program to demonstrates
// the compareAndSet() 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.compareAndSet(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 to demonstrates
// the compareAndSet() 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.compareAndSet(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

参考资料: https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/atomic/AtomicInteger.html#compareAndSet-

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程