当前位置:网站首页>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.
边栏推荐
猜你喜欢

语音聊天app——如何规范开发流程?

软件设计师考前20问,注意啦!!

What are the advantages of MRO purchasing website for industrial products? One article will help you understand

B2B2C系统亮点是什么?如何助力珠宝首饰企业打造全渠道多商户商城管理体系

ES(8.1)认证题目

初识SuperMap iDesktop

选择供应商服务系统,是大健康产业企业迈向数字化转型的第一步

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

Installing MySQL for Linux operating system (centos7)

Flink - checkpoint Failure reason: Not all required tasks are currently running
随机推荐
ELK实时日志分析平台
CGAL编译错误
19. 删除链表的倒数第 N 个结点
Etcd (highly available kV database)
️雄关漫道真如铁,而今迈步从头越️
医药行业数字化建设,箭在弦上
What kind of knowledge payment system functions are more conducive to the development of the platform and lecturers?
10 minute quick start EVs [play Huawei cloud]
Holy Grail of web and double wing layout, float, clear, both
2022 uni app parsing token standard - use jsrsasign - climb the pit
Digital construction of pharmaceutical industry is on the verge
语音聊天app——如何规范开发流程?
【云驻共创】企业数字化转型,华为云咨询与你同行
Voice chat app - how to standardize the development process?
JWT 登录认证 + Token 自动续期方案,写得太好了!
Redis面试题必知必会
Kubernetes
Illustrate three mainstream enterprise architecture models (recommended collection!)
(1)机器学习概念总结
【学习笔记】border与period