// Java原子类示例代码
import java.util.concurrent.atomic.AtomicInteger;
public class AtomicExample {
// 创建一个 AtomicInteger 对象,初始值为 0
private static final AtomicInteger atomicInt = new AtomicInteger(0);
public static void main(String[] args) {
// 使用 getAndIncrement 方法进行自增操作
System.out.println("Initial value: " + atomicInt.get()); // 输出: Initial value: 0
int incrementedValue = atomicInt.getAndIncrement();
System.out.println("After getAndIncrement: " + incrementedValue); // 输出: After getAndIncrement: 0
System.out.println("Current value after increment: " + atomicInt.get()); // 输出: Current value after increment: 1
// 使用 compareAndSet 方法进行条件更新
boolean isUpdated = atomicInt.compareAndSet(1, 100);
System.out.println("Is updated to 100: " + isUpdated); // 输出: Is updated to 100: true
System.out.println("Current value after compareAndSet: " + atomicInt.get()); // 输出: Current value after compareAndSet: 100
// 尝试将值从 100 更新为 200,但此时值不是 100,所以不会更新
boolean failedUpdate = atomicInt.compareAndSet(101, 200);
System.out.println("Failed update attempt: " + failedUpdate); // 输出: Failed update attempt: false
System.out.println("Current value remains: " + atomicInt.get()); // 输出: Current value remains: 100
}
}
expected,如果是,则将值设置为 newValue。这也是一个原子操作,常用于实现无锁算法。上一篇:java校验字符串是否为数字
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站