当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Java AtomicBoolean compareAndSet()用法及代码示例


java.util.concurrent.atomic.AtomicBoolean.compareAndSet()是java中的一种内置方法,如果当前值等于参数给定的期望值,则将值设置为参数中的传递值。该函数返回一个布尔值,该布尔值使我们了解更新是否完成。

用法:

public final boolean compareAndSet(boolean expect, boolean val)



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

  • expect:它指定原子对象应为的值。
  • val:如果原子布尔等于期望值,它指定要更新的值。

返回值:该函数返回一个布尔值,成功则返回true,否则返回false。

以下示例程序旨在说明上述函数:

示例1:

// Java Program to demonstrates 
// the compareAndSet() function 
  
import java.util.concurrent.atomic.AtomicBoolean; 
  
public class GFG { 
    public static void main(String args[]) 
    { 
  
        // Initially value as false 
        AtomicBoolean val = new AtomicBoolean(false); 
  
        // Prints the updated value 
        System.out.println("Previous value: "
                           + val); 
  
        // Checks if previous value was false 
        // and then updates it 
        boolean res = val.compareAndSet(false, true); 
  
        // 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: false
The value was updated and it is true

示例2:

// Java Program to demonstrates 
// the compareAndSet() function 
  
import java.util.concurrent.atomic.AtomicBoolean; 
  
public class GFG { 
    public static void main(String args[]) 
    { 
  
        // Initially value as true 
        AtomicBoolean val = new AtomicBoolean(true); 
  
        // Prints the updated value 
        System.out.println("Previous value: "
                           + val); 
  
        // Checks if previous value was true 
        // and then updates it 
        boolean res = val.compareAndSet(true, false); 
  
        // 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: true
The value was updated and it is false

参考: https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/atomic/AtomicBoolean.html#compareAndSet(boolean, %20boolean)



相关用法


注:本文由纯净天空筛选整理自gopaldave大神的英文原创作品 AtomicBoolean compareAndSet() method in Java with Examples。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。