百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 技术分类 > 正文

Java AtomicInteger操作详解

ztj100 2025-05-23 21:35 12 浏览 0 评论

介绍

AtomicInteger 是使用CAS实现的对 int 类型进行原子操作的类。

什么是CompareAndSwap(CAS? 即比较并替换,实现并发算法时常用到的一种技术。CAS操作包含三个操作数——内存位置、预期原值及新值。执行CAS操作的时候,将内存位置的值与预期原值比较,如果相匹配,那么处理器会自动将该位置值更新为新值,否则,处理器不做任何操作。CAS是一条CPU的原子指令(cmpxchg指令),不会造成所谓的数据不一致问题,AtomicBoolean 调用 Unsafe 类提供的CAS方法(如compareAndSwapXXX)实现了原子操作。要了解 Unsafe 的基本运用,请查看 《Unsafe的基本操作》

基本操作

AtomicInteger 具有与 AtomicBoolean 相同的方法,如下:

/**
 * Gets the current value.
 *
 * @return the current value
 */
public final int get() {
    return value;
}

/**
 * Sets to the given value.
 *
 * @param newValue the new value
 */
public final void set(int newValue) {
    value = newValue;
}

/**
 * Eventually sets to the given value.
 *
 * @param newValue the new value
 * @since 1.6
 */
public final void lazySet(int newValue) {
    unsafe.putOrderedInt(this, valueOffset, newValue);
}

/**
 * Atomically sets to the given value and returns the old value.
 *
 * @param newValue the new value
 * @return the previous value
 */
public final int getAndSet(int newValue) {
    return unsafe.getAndSetInt(this, valueOffset, newValue);
}

/**
 * Atomically sets the value to the given updated value
 * if the current value {@code ==} the expected value.
 *
 * @param expect the expected value
 * @param update the new value
 * @return {@code true} if successful. False return indicates that
 * the actual value was not equal to the expected value.
 */
public final boolean compareAndSet(int expect, int update) {
    return unsafe.compareAndSwapInt(this, valueOffset, expect, update);
}

/**
 * Atomically sets the value to the given updated value
 * if the current value {@code ==} the expected value.
 *
 * <p><a href="package-summary.html#weakCompareAndSet">May fail
 * spuriously and does not provide ordering guarantees</a>, so is
 * only rarely an appropriate alternative to {@code compareAndSet}.
 *
 * @param expect the expected value
 * @param update the new value
 * @return {@code true} if successful
 */
public final boolean weakCompareAndSet(int expect, int update) {
    return unsafe.compareAndSwapInt(this, valueOffset, expect, update);
}

此部分操作请查看《AtomicBoolean操作详解及原理分析》

1、getAndIncrement

将当前值加1,并返回加1前的值。

AtomicInteger atomicInteger = new AtomicInteger(1);
int getAndIncrement = atomicInteger.getAndIncrement();
int currentValue = atomicInteger.get();
System.out.println(getAndIncrement); // 输出:1(加1之前的值)
System.out.println(currentValue); // 输出:2(当前值)

2、getAndDecrement

将当前值减1,并返回减1前的值。

AtomicInteger atomicInteger = new AtomicInteger(1);
int getAndDecrement = atomicInteger.getAndDecrement();
int currentValue = atomicInteger.get();
System.out.println(getAndDecrement); // 输出:1(加1之前的值)
System.out.println(currentValue); // 输出:0(当前值)

3、getAndAdd

getAndIncrement 类似,不过 getAndAdd 可以自定义增加一个数值。

AtomicInteger atomicInteger = new AtomicInteger(1);
int getAndAdd = atomicInteger.getAndAdd(10);
int currentValue = atomicInteger.get();
System.out.println(getAndAdd); // 输出:1(加1之前的值)
System.out.println(currentValue); // 输出:11(当前值)

4、incrementAndGet

getAndIncrement 相反,incrementAndGet 是将当前值加1,并返回加1后的值。

AtomicInteger atomicInteger = new AtomicInteger(1);
int incrementAndGet = atomicInteger.incrementAndGet();
int currentValue = atomicInteger.get();
System.out.println(incrementAndGet); // 输出:2(加1之后的值)
System.out.println(currentValue); // 输出:2(当前值)

5、decrementAndGet

getAndDecrement 相反,decrementAndGet 是将当前值减1,并返回减1后的值。

AtomicInteger atomicInteger = new AtomicInteger(1);
int decrementAndGet = atomicInteger.decrementAndGet();
int currentValue = atomicInteger.get();
System.out.println(decrementAndGet); // 输出:0(减1之后的值)
System.out.println(currentValue); // 输出:0(当前值)

6、addAndGet

getAndAdd 相反,addAndGet 是将当前值加上给定的数值,并返回增加后的值。

AtomicInteger atomicInteger = new AtomicInteger(1);
int addAndGet = atomicInteger.addAndGet(10);
int currentValue = atomicInteger.get();
System.out.println(addAndGet); // 输出:11(增加之后的值)
System.out.println(currentValue); // 输出:11(当前值)

7、getAndUpdate

接收一个函数作为参数,通过函数来更新当前值,并且返回更新前的值。源码:

public final int getAndUpdate(IntUnaryOperator updateFunction) {
    int prev, next;
    do {
        prev = get();
        next = updateFunction.applyAsInt(prev);
    } while (!compareAndSet(prev, next));
    return prev;
}

使用示例:

AtomicInteger atomicInteger = new AtomicInteger(1);
int getAndUpdate = atomicInteger.getAndUpdate(e -> e * 100 + 10);
int currentValue = atomicInteger.get();
System.out.println(getAndUpdate); // 输出:1(更新之前的值)
System.out.println(currentValue); // 输出:110(当前值)

8、updateAndGet

接收一个函数作为参数,通过函数来更新当前值,并且返回更新后的值。

示例:

AtomicInteger atomicInteger = new AtomicInteger(1);
int updateAndGet = atomicInteger.updateAndGet(e -> e * 100 + 10);
int currentValue = atomicInteger.get();
System.out.println(updateAndGet); // 输出:110(更新之后的值)
System.out.println(currentValue); // 输出:110(当前值)

9、getAndAccumulate

给定一个数值和一个函数,通过函数对当前值和给定的值进行计算,将计算结果设置为当前值,并返回计算前的值。源码如下:

public final int getAndAccumulate(int x,
                                  IntBinaryOperator accumulatorFunction) {
    int prev, next;
    do {
        prev = get();
        next = accumulatorFunction.applyAsInt(prev, x);
    } while (!compareAndSet(prev, next));
    return prev;
}

示例:

AtomicInteger atomicInteger = new AtomicInteger(4);
int getAndAccumulate = atomicInteger.getAndAccumulate(3, (left, right) -> left * right + 5);
int currentValue = atomicInteger.get();
System.out.println(getAndAccumulate); // 输出:4(计算之后的值)
System.out.println(currentValue); // 输出:17(当前值)

10、accumulateAndGet

给定一个数值和一个函数,通过函数对当前值和给定的值进行计算,将计算结果设置为当前值,并返回计算后的值。

AtomicInteger atomicInteger = new AtomicInteger(4);
int accumulateAndGet = atomicInteger.accumulateAndGet(3, (left, right) -> left * right + 5);
int currentValue = atomicInteger.get();
System.out.println(accumulateAndGet); // 输出:17(计算之后的值)
System.out.println(currentValue); // 输出:17(当前值)

相关推荐

拒绝躺平,如何使用AOP的环绕通知实现分布式锁

如何在分布式环境下,像用synchronized关键字那样使用分布式锁。比如开发一个注解,叫@DistributionLock,作用于一个方法函数上,每次调方法前加锁,调完之后自动释放锁。可以利用Sp...

「解锁新姿势」 兄dei,你代码需要优化了

前言在我们平常开发过程中,由于项目时间紧张,代码可以用就好,往往会忽视代码的质量问题。甚至有些复制粘贴过来,不加以整理规范。往往导致项目后期难以维护,更别说后续接手项目的人。所以啊,我们要编写出优雅的...

消息队列核心面试点讲解(消息队列面试题)

Rocketmq消息不丢失一、前言RocketMQ可以理解成一个特殊的存储系统,这个存储系统特殊之处数据是一般只会被使用一次,这种情况下,如何保证这个被消费一次的消息不丢失是非常重要的。本文将分析Ro...

秒杀系统—4.第二版升级优化的技术文档二

大纲7.秒杀系统的秒杀活动服务实现...

SpringBoot JPA动态查询与Specification详解:从基础到高级实战

一、JPA动态查询概述1.1什么是动态查询动态查询是指根据运行时条件构建的查询,与静态查询(如@Query注解或命名查询)相对。在业务系统中,80%的查询需求都是动态的,例如电商系统中的商品筛选、订...

Java常用工具类技术文档(java常用工具类技术文档有哪些)

一、概述Java工具类(UtilityClasses)是封装了通用功能的静态方法集合,能够简化代码、提高开发效率。本文整理Java原生及常用第三方库(如ApacheCommons、GoogleG...

Guava 之Joiner 拼接字符串和Map(字符串拼接join的用法)

Guave是一个强大的的工具集合,今天给大家介绍一下,常用的拼接字符串的方法,当然JDK也有方便的拼接字符串的方式,本文主要介绍guava的,可以对比使用基本的拼接的话可以如下操作...

SpringBoot怎么整合Redis,监听Key过期事件?

一、修改Redis配置文件1、在Redis的安装目录2、找到redis.windows.conf文件,搜索“notify-keyspace-events”...

如何使用Python将多个excel文件数据快速汇总?

在数据分析和处理的过程中,Excel文件是我们经常会遇到的数据格式之一。本文将通过一个具体的示例,展示如何使用Python和Pandas库来读取、合并和处理多个Excel文件的数据,并最终生成一个包含...

利用Pandas高效处理百万级数据集,速度提升10倍的秘密武器

处理大规模数据集,尤其是百万级别的数据量,对效率的要求非常高。使用Pandas时,可以通过一些策略和技巧显著提高数据处理的速度。以下是一些关键的方法,帮助你使用Pandas高效地处理大型数据集,从而实...

Python进阶-Day 25: 数据分析基础

目标:掌握Pandas和NumPy的基本操作,学习如何分析CSV数据集并生成报告。课程内容...

Pandas 入门教程 - 第五课: 高级数据操作

在前几节课中,我们学习了如何使用Pandas进行数据操作和可视化。在这一课中,我们将进一步探索一些高级的数据操作技巧,包括数据透视、分组聚合、时间序列处理以及高级索引和切片。高级索引和切片...

原来这才是Pandas!(原来这才是薯片真正的吃法)

听到一些人说,Pandas语法太乱、太杂了,根本记不住。...

python(pandas + numpy)数据分析的基础

数据NaN值排查,统计,排序...

利用Python进行数据分组/数据透视表

1.数据分组源数据表如下所示:1.1分组键是列名分组键是列名时直接将某一列或多列的列名传给groupby()方法,groupby()方法就会按照这一列或多列进行分组。按照一列进行分组...

取消回复欢迎 发表评论: