Java.util.concurrent.atomic.AtomicLong.weakCompareAndSet()是Java中的一種內置方法,如果當前值等於參數給定的期望值,則將值設置為參數中的傳遞值。該函數返回一個布爾值,該布爾值使我們了解更新是否完成。
用法:
public final boolean weakCompareAndSet(long expect, long val)
參數:該函數接受兩個強製性參數,如下所述:
- expect:指定原子對象應為的值。
- val:指定如果原子長等於期望值則要更新的值。
返回值:該函數返回一個布爾值,成功則返回true,否則返回false。
以下示例程序旨在說明上述方法:
示例1:
// Java program that demonstrates
// the weakCompareAndSet() function
import java.util.concurrent.atomic.AtomicLong;
public class GFG {
public static void main(String args[])
{
// Initially value as 0
AtomicLong val = new AtomicLong(0);
// Prlongs 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.AtomicLong;
public class GFG {
public static void main(String args[])
{
// Initially value as 0
AtomicLong val = new AtomicLong(0);
// Prlongs 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 AtomicInteger weakCompareAndSet()用法及代碼示例
- Java AtomicReferenceArray weakCompareAndSet()用法及代碼示例
- Java AtomicReference weakCompareAndSet()用法及代碼示例
- Java AtomicLong set()用法及代碼示例
- Java AtomicLong get()用法及代碼示例
- Java AtomicLong decrementAndGet()用法及代碼示例
- Java AtomicLong toString()用法及代碼示例
- Java AtomicLong doubleValue()用法及代碼示例
- Java AtomicLong compareAndSet()用法及代碼示例
- Java AtomicLong intValue()用法及代碼示例
- Java AtomicLong longValue()用法及代碼示例
- Java AtomicLong addAndGet()用法及代碼示例
- Java AtomicLong getAndAdd()用法及代碼示例
- Java AtomicLong incrementAndGet()用法及代碼示例
- Java AtomicLong floatValue()用法及代碼示例
注:本文由純淨天空篩選整理自gopaldave大神的英文原創作品 AtomicLong weakCompareAndSet() method in Java with examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。