Java AtomicInteger操作详解
ztj100 2025-05-23 21:35 23 浏览 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(当前值)
相关推荐
- 其实TensorFlow真的很水无非就这30篇熬夜练
-
好的!以下是TensorFlow需要掌握的核心内容,用列表形式呈现,简洁清晰(含表情符号,<300字):1.基础概念与环境TensorFlow架构(计算图、会话->EagerE...
- 交叉验证和超参数调整:如何优化你的机器学习模型
-
准确预测Fitbit的睡眠得分在本文的前两部分中,我获取了Fitbit的睡眠数据并对其进行预处理,将这些数据分为训练集、验证集和测试集,除此之外,我还训练了三种不同的机器学习模型并比较了它们的性能。在...
- 机器学习交叉验证全指南:原理、类型与实战技巧
-
机器学习模型常常需要大量数据,但它们如何与实时新数据协同工作也同样关键。交叉验证是一种通过将数据集分成若干部分、在部分数据上训练模型、在其余数据上测试模型的方法,用来检验模型的表现。这有助于发现过拟合...
- 深度学习中的类别激活热图可视化
-
作者:ValentinaAlto编译:ronghuaiyang导读使用Keras实现图像分类中的激活热图的可视化,帮助更有针对性...
- 超强,必会的机器学习评估指标
-
大侠幸会,在下全网同名[算法金]0基础转AI上岸,多个算法赛Top[日更万日,让更多人享受智能乐趣]构建机器学习模型的关键步骤是检查其性能,这是通过使用验证指标来完成的。选择正确的验证指...
- 机器学习入门教程-第六课:监督学习与非监督学习
-
1.回顾与引入上节课我们谈到了机器学习的一些实战技巧,比如如何处理数据、选择模型以及调整参数。今天,我们将更深入地探讨机器学习的两大类:监督学习和非监督学习。2.监督学习监督学习就像是有老师的教学...
- Python 模型部署不用愁!容器化实战,5 分钟搞定环境配置
-
你是不是也遇到过这种糟心事:花了好几天训练出的Python模型,在自己电脑上跑得顺顺当当,一放到服务器就各种报错。要么是Python版本不对,要么是依赖库冲突,折腾半天还是用不了。别再喊“我...
- 神经网络与传统统计方法的简单对比
-
传统的统计方法如...
- 自回归滞后模型进行多变量时间序列预测
-
下图显示了关于不同类型葡萄酒销量的月度多元时间序列。每种葡萄酒类型都是时间序列中的一个变量。假设要预测其中一个变量。比如,sparklingwine。如何建立一个模型来进行预测呢?一种常见的方...
- 苹果AI策略:慢哲学——科技行业的“长期主义”试金石
-
苹果AI策略的深度原创分析,结合技术伦理、商业逻辑与行业博弈,揭示其“慢哲学”背后的战略智慧:一、反常之举:AI狂潮中的“逆行者”当科技巨头深陷AI军备竞赛,苹果的克制显得格格不入:功能延期:App...
- 时间序列预测全攻略,6大模型代码实操
-
如果你对数据分析感兴趣,希望学习更多的方法论,希望听听经验分享,欢迎移步宝藏公众号...
你 发表评论:
欢迎- 一周热门
- 最近发表
- 标签列表
-
- idea eval reset (50)
- vue dispatch (70)
- update canceled (42)
- order by asc (53)
- spring gateway (67)
- 简单代码编程 贪吃蛇 (40)
- transforms.resize (33)
- redisson trylock (35)
- 卸载node (35)
- np.reshape (33)
- torch.arange (34)
- npm 源 (35)
- vue3 deep (35)
- win10 ssh (35)
- vue foreach (34)
- idea设置编码为utf8 (35)
- vue 数组添加元素 (34)
- std find (34)
- tablefield注解用途 (35)
- python str转json (34)
- java websocket客户端 (34)
- tensor.view (34)
- java jackson (34)
- vmware17pro最新密钥 (34)
- mysql单表最大数据量 (35)