当前位置:网站首页>Detailed explanation of thread synchronization volatile and synchronized
Detailed explanation of thread synchronization volatile and synchronized
2022-07-28 10:14:00 【Hua Weiyun】
0. Preface
It's very likely that you will encounter such a problem during the interview : Use volatile modification int Type variable i, Multiple threads running at the same time i++ operation , Is this thread safe ? Mention thread safety 、 Thread synchronization , We often think of two keywords :volatile and synchronized, So what's the difference between the two ?
1. volatile And synchronized Introduce
volatile Is a variable modifier , The variables it modifies have visibility ( Visibility means that once a thread is modified it should be volatile Decorated variable , It will ensure that the modified value will be immediately updated to physical memory , When there are other threads that need To read , You can get the modified value immediately ). stay Java In order to speed up the efficiency of the program , Operations on some variables are usually in registers or CPU On Cache , Then it will be synchronized to physical memory , And added volatile The variable of modifier is to read and write physical memory directly .
Please check the following 3.1, Help you understand .
volatile Instruction rearrangement can be prohibited , What is instruction reordering ? Generally speaking , In order to improve the efficiency of the program , The input code may be optimized , It does not guarantee that the execution sequence of each statement in the program is the same as that in the code , But it will ensure that the final execution result of the program is consistent with the sequential execution result of the code . Instruction reordering does not affect the execution of a single thread , But it will affect the correctness of thread concurrent execution .
however volatile It can ensure order . The program runs to volatile When reading or writing variables , In the preceding statement , The change operation must have been completed , And the results are already visible for later operations , The operation behind it has not been carried out yet .
See the following for examples 3.2, Help you understand .
synchronized It works on a piece of code or method , Using this modifier can ensure visibility ( adopt synchronized and Lock It also ensures visibility ,synchronized and Lock It can guarantee that only one thread can acquire lock and execute synchronization code at the same time , And the changes to variables will be flushed into physical memory before releasing the lock . So you can guarantee visibility ), It can also guarantee atomicity ( Atomicity is manifested in either not executing , Or carry it out to the end ). Sometimes you have to use synchronized, They can't be used volatile.
See the following for examples 3.3, Help you understand .
2. summary
(1) So we can see volatile Although it has visibility, it doesn't guarantee atomicity .
(2)synchronized Keyword is to prevent multiple threads from executing a piece of code at the same time , Then it will affect the efficiency of program execution , and volatile Keywords perform better than... In some cases synchronized, But be careful volatile Keywords are irreplaceable synchronized Keywords , because volatile Keyword does not guarantee atomicity of operation .
3. volatile And synchronized Examples of usage scenarios ( Combined with 1 Part of understanding and learning )
3.1 volatile Examples of use of
Threads execute run() We need to keep doing something in the thread , such as while loop , So how to stop the thread at this time ? If what the thread does is not time-consuming , Then just use one sign . If you need to exit , call setStop() that will do . Here we use keywords volatile, The purpose of this keyword is to modify isStop Value , So in while The modified value can be read immediately in the loop .
If what the thread does is time-consuming , Then you can use interrupt Method to terminate a thread .
3.2 volatile Examples of use of
Because instruction reordering , It is possible to say 2 Will be in the sentence 1 Before execution , May lead to context It's not initialized yet , And threads 2 Use uninitialized context To operate , Cause program error .
If you use volatile Key words to inited Variable to modify , There would be no such problem , Because when the statement is executed 2 when , There must be a guarantee that context It's initialized .
3.3 You have to use synchronized They can't be used volatile Scene
In the example, use new 了 10 Threads , Call... Separately 1000 Time increase() Method , The results of each run are inconsistent , All of them are smaller than 10000 The number of . The auto increment operation is not an atomic operation ,volatile There is no guarantee of atomicity . Back to the example at the beginning of the article , Use volatile modification int Type variable i, Multiple threads running at the same time i++ operation . For example, there are two threads A and B Yes volatile Embellished i Conduct i++ operation ,i The initial value of 0,A Threads execute i++ Just read i Value 0, Just switch to B Thread ,B Threads ( From memory ) Read i Values are 0, And then switch to A The thread continues to execute i++ operation , After completion i for 1 了 , Then switch to B Threads , Because I've read it before , So keep going i++ operation , The final result i for 1 了 . The same can explain why the result of each run is less than 10000 The number of .
But use synchronized Modify some codes as follows , It can ensure that only one thread can acquire the lock and execute the synchronization code at the same time . The result of the operation must be 10000.
边栏推荐
- Illustrate three mainstream enterprise architecture models (recommended collection!)
- On July 13, 2021, we collapsed like this
- Redis设计规范
- 13 probability distributions that must be understood in deep learning
- LinkedList源码按摩,啊舒服
- Irregular area of OSPF, LSA and serial number
- Holy Grail of web and double wing layout, float, clear, both
- leetcode——旋转数组的最小数字
- (1)机器学习概念总结
- 2021-10-13arx
猜你喜欢

ADVANCE.AI出海指南助力企业出海印尼,掌握东南亚市场半边天

Thinking and summary of technical personnel | R & D Efficiency

Xiao Hei stands up again and looks at leetcode:653. Sum of two IV - enter BST

Guangzhou metro line 14 xinshixu station is under construction, and residents in Baiyun District are about to start a double line transfer mode!

什么样的知识付费系统功能,更有利于平台与讲师发展?

TCP Basics

医药行业数字化建设,箭在弦上

Digital transformation scheme of real estate: all-round digital intelligence system operation, helping real estate enterprises improve the effectiveness of management and control

建筑建材行业B2B电子商务网站方案:赋能建材企业转型升级,实现降本提效

15、判断二维数组中是否存在目标值
随机推荐
ADVANCE.AI出海指南助力企业出海印尼,掌握东南亚市场半边天
JWT 登录认证 + Token 自动续期方案,写得太好了!
Etcd (highly available kV database)
Redis设计规范
2022-uni-app解析token标准的方式-使用jsrsasign-爬坑过了
基于ModelArts续写最伟大的作品【玩转华为云】
定了!就在7月30日!
【JZOF】15二进制中1的位数
图解 3 种主流企业架构模式(建议收藏!)
ASP. Net core 6 framework unveiling example demonstration [29]: building a file server
语音聊天app——如何规范开发流程?
记录一次idea中的父子项目修改project与module名称,亲测!
IE兼容性问题处理
9、删除链表中节点
Openatom openharmony sub forum, see you today at 14:00! Wonderful release of memorabilia attached
[jzof] 15 bits of 1 in binary
房地产数字化转型方案:全方位数智化系统运营,助力房企管控实效提升
14、双指针——盛最多水的容器
02.1.2.逻辑类型 bool
【云驻共创】企业数字化转型,华为云咨询与你同行