当前位置:网站首页>Detailed explanation of AtomicInteger
Detailed explanation of AtomicInteger
2022-08-02 21:04:00 【i attack siege lion】
一、什么是AtomicInteger
AtomicInteger类是系统底层保护的int类型,通过对int类型的数据进行封装,提供执行方法的控制进行值的原子操作.AtomicInteger它不能当作Integer来使用
从JAVA 1.5开始,AtomicInteger 属于java.util.concurrent.atomic 包下的一个类
.
二、AtomicInteger的作用
在Java中的运算操作,例如自增或自减,在多线程环境下就是线程不安全的.num++解析为num=num+1,Java程序会把算式分为3个操作,获取值,计算值,赋予值,明显,这个操作不具备原子性,多线程并发共享这个变量时必然会出现问题.
一个线程计算出值后,还未重新给变量赋值,另一个线程有来读取到这个值,就会造成线程不安全的问题.
想让线程安全,往往可能需要通过加锁的方式去保证线程安全,但是,加锁对性能会有很大的影响.
而AtomicInteger原子类型就是让程序在不加锁的时候也能保障线程安全,案例如下:
static int b =0;
public static void main(String[] args) throws InterruptedException {
AtomicInteger a = new AtomicInteger(0);
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < 10000; i++) {
a.incrementAndGet();
b++;
}
}
});
t1.start();
Thread t2 = new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < 10000; i++) {
a.incrementAndGet();
b++;
}
}
});
t2.start();
Thread.sleep(1000);
System.out.println("a="+a);
System.out.println("b="+b);
}
输出结果:
根据结果可见,使用AtomicInteger在多线程进行自增运算的时候,是线程安全的,而普通的int在自增的时候则是线程不安全的.
incrementAndGet()方法,是AtomicInteger的自增方法,会让AtomicInteger的值+1.
三、 原子方式执行加法和减法操作的方法
- addAndGet()- 以原子方式将给定值添加到当前值,并在添加后返回新值.
- getAndAdd() - 以原子方式将给定值添加到当前值并返回旧值.
- incrementAndGet()- 以原子方式将当前值递增1并在递增后返回新值.它相当于i ++操作.
- getAndIncrement() - 以原子方式递增当前值并返回旧值.它相当于++ i操作.
- decrementAndGet()- 原子地将当前值减1并在减量后返回新值.它等同于i-操作.
- getAndDecrement() - 以原子方式递减当前值并返回旧值.它相当于-i操作.
边栏推荐
猜你喜欢

shell中awk命令的if条件语句引入外置变量

Monitor is easy to Mars debut: distributed operations help TOP3000 across management gap

【秒杀办法】根据二叉树的先序遍历、中序遍历、后序遍历快速创建二叉树

“12306”的架构到底有多牛逼?

redis summary_distributed cache

下载mysql的源码包

Redis总结_实战篇

Five keys to a successful Industrial IoT deployment

为何国内年轻人都抢购iPhone,因为它更实惠也更亲民

来亲自手搭一个ResNet18网络
随机推荐
深入理解IO流(第一篇)
LeetCode 2349. 设计数字容器系统(SortedSet)
golang刷leetcode 经典(4) 实现跳表
LiveGBS国标GB/T28181流媒体平台支持主子码流切换主码流stream/streamprofile
From the technical panorama to the actual scene, analyze the evolutionary breakthrough of "narrowband high-definition"
mongodb的游标
sed 命令
LeetCode 2343. 裁剪数字后查询第 K 小的数字
54.【system系统互动函数大总结】
What skills are the most practical for college students in communications?
Code Inspection for DevOps
2022最新版SSM源码分析:一套教程助你深入理解底层原理,提高核心竞争力!
共享平台如何提高财务的分账记账效率?
How can services start smoothly under tens of millions of QPS
Mysql和Redis如何保证数据一致性
我的递归从不爆栈
Remember the stuck analysis of an industrial automation control system in .NET
golang源码分析(33)pollFD
KunlunBase 1.0 is released!
Go编译原理系列6(类型检查)