当前位置:网站首页>多线程 里面 使用AtomicInteger类,保证线程安全
多线程 里面 使用AtomicInteger类,保证线程安全
2022-07-21 19:02:00 【一天不写代码难受】
1 什么叫做线程安全
假设我们的网站要统计用户人数,我们需要通过变量的自增来实现:count++; 这个操作存在线程安全问题:
最后统计的人数是少的;
2 问题分析
count++的操作分为三步:
读取count的值
计算count+1的值
把新值存入count
假设count值为100,两个线程A和B都执行了操作1,
再同时执行操作2,A先进行操作3,这时count值为101,
B再执行操作3,之前B读取的值是100,执行完操作3后B
的结果还是101,这样数据出现了问题。因为上面的操作
不是原子的,可以分开执行。
3 解决
AtomicInteger出现解决了上面的问题,使用它来执行统计:
static AtomicInteger at = new AtomicInteger(0);
public static void main(String[] args) {
for(int i = 0;i < 10000;i++){
new Thread(()->{
at.incrementAndGet();}).start();
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("count = " + at.get());
}
AtomicInteger 源码里面有关键字volatile;
它确保对volatile字段的更新以可预见的方式告知其他的线程。简而言之volatile 的作用是当一个线程修改了变量时,另一个线程可以读取到这个修改后的值。
4 总结
AtomicInteger能够实现整型数据的原子操作,在多线程并发的环境下能保证数据安全,而且内部使用乐观锁实现,比使用锁机制的并发性能高;
volatile保证了一个线程修改数据时,其它线程也能看到数据的修改
CAS操作保证了数据修改的安全性
5 线程统计失败个数
多个线程执行一段逻辑,统计有多少个线程失败了
ConcurrentMap<Integer, AtomicInteger> jobTimeoutCountMap = new ConcurrentHashMap<>();
//分10个线程,每个线程自增2000次
for (int i = 0; i < 10; i++) {
new Thread(new Runnable() {
public void run() {
for (int i = 0; i < 2000; i++) {
AtomicInteger timeoutCount = jobTimeoutCountMap.putIfAbsent(22, new AtomicInteger(1));
if (timeoutCount != null) {
// 记录慢任务慢的次数
timeoutCount.incrementAndGet();
}
}
}
}).start();
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(jobTimeoutCountMap.get(22));
边栏推荐
- Dangdang: the sense of existence in "chaos"
- Hd06-asemi patch rectifier bridge hd06
- 当MCU死机了,先把硬件抓过来~
- 软件测试过程的持续改进
- 网页保存为pdf神器(可自定义编辑)—Print Edit WE
- What is cloud rendering? How fast is the rendering speed? Yiwen tells you
- 简单弄懂Saas是什么? Saas与传统软件有什么区别?
- Understanding and operation of pointer
- 【Cicadaplayer】vs2019(V142) X64 FFMEPG : error C2169: “lrintf”: 内部函数,不能定义
- Execution failed for task ‘:app:kaptDevDebugKotlin‘.
猜你喜欢
Std:: thread combined with class object
How does Apache, the world's largest open source foundation, work?
壁纸背景墙/头像/动态壁纸小程序源码-支持用户投稿-带部分采集功能+搭建教程
什么是云渲染?渲染速度有多快?一文告诉你
视频剪辑调色软件 DaVinci Resolve 18 正式版发布
Service & Endpoint
2022开源PHP留言反馈管理系统 v2.0
Autojs learning - achieve file download progress
使用cpolar建立一个商业网站(3)
Recommendation of top 10 mainstream pressure / load / performance testing tools
随机推荐
能量原理与变分法笔记06:高阶导数的变分问题(包含函数的高阶导数)
Hd06-asemi patch rectifier bridge hd06
百度飞桨EasyDL X 韦士肯:看轴承质检如何装上“AI之眼”
After leaving Google, the former head of go language changed to a small company
罐子(kuangbin专题)
Energy principle and variational method note 03: prove the shortest straight line between two points
集合(Properties)
day02-2
Unity Scrollview scroll to the specified position
梨花带雨音乐播放器3.91源码开源(网站添加背景音乐)
HD06-ASEMI贴片整流桥HD06
Recommend the source code of the finished live broadcast, and set the system date, time and time zone
How to quickly develop a simple and practical MES system?
Use of get method of jsonobject
Some visualization methods of CNN
std::thread 与类对象结合
当MCU死机了,先把硬件抓过来~
Ingress
Microsoft gives up "blocking" commercial open source!
能量原理与变分法笔记08: 虚功原理的推导