Java AtomicInteger compareAndSet() 方法

2025 年 3 月 20 日 | 阅读 2 分钟

Java AtomicInteger 类的 compareAndSet() 方法会比较当前值和期望值。如果两个值相等,则会更新该值。

语法

参数

expect (期望值): 这是期望的值

update (更新值): 这是新的值

返回

如果期望值等于当前值,此方法将返回一个新的 atomicInteger 值。

示例 1

输出

the updated number: 444

示例 2

输出

the updated number:222

在上面的示例中,期望值不等于新值,因此值未被更新,仍然保持为初始值。

示例 3

输出

the updated number: 0

示例 4

输出

the updated number: 100

示例 5

输出

the updated number: -2
 
下一主题Java AtomicInteger