说明:本篇文章是在阅读《Java 并发编程艺术》过程中的一些笔记和分析 文章来源:https://www.iteye.com/blog/xiaoheng-2509522
该项目的地址:https://github.com/xiaoheng1/concurrent-programming
欢迎有兴趣的小伙伴加入,一起讨论、分析,共同进步!
atomic 包中的 13 个类,属于 4 中类型的原子更新方式.
atomic 包里的类基本都是使用 Unsafe 实现的包装类.
本类以 AtomicInteger 进行讲解:
int addAndGet(int delta) 以原子方式将输入的数值与实例中的值相加,并返回结果
boolean compareAndSet(int expect, int update) 如果输入的数值等于预期值,则以原子的方式将该值设置为输入的值.
int getAndIncrement() 以原子方式将当前值加 1,注意,这里返回的是自增前的值.
void lazySet(int newValue) 最终会设置成 newValue,使用 lazySet 设置值后,可能导致其他线程在之后的一小段时间内还是可以读到 旧值.
int getAndSet(int newValue) 以原子方式设置为 newValue 的值,并返回旧值.
getAndIncrement 是如何实现原子操作的了?
public final int getAndIncrement() {
for (;;) {
int current = get();
int next = current + 1;
if (compareAndSet(current, next))
return current;
}
}
我们可以看到,它的实现原理是死循环 + CAS.
AtomicIntegerArray 类提供方法如下:(1) int addAndGet(int i, int delta) 以原子方式将输入值与数组中的索引 i 的元素相加 (2) boolean compareAndSet(int i, int expect, int update) 如果当前值等于预期值,则以原子方式将数组位置 i 的元素设置成 update 值.
原子更新基本类型的 AtomicInteger, 只能更新一个变量,如果要原子更新多个变量,就需要使用这个原子更新引用类型提供的类.
推荐阅读
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有