Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is the difference between synchronized and volatile keywords

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/02 Report--

What is the difference between synchronized and volatile keywords, many novices are not very clear about this, in order to help you solve this problem, the following editor will explain for you in detail, people with this need can come to learn, I hope you can gain something.

Synchronized

Synchronized can decorate methods and code blocks

Threads block when multithreading executes synchronized methods

Synchronized can guarantee the atomicity of threads.

Volatile

Volatile has higher performance than synchronized.

Volatile can only modify variables

Threads do not block when multithreading accesses volatile

Volatile cannot guarantee the atomicity of threads.

Thread atomicity refers to operations that cannot be split. To put it bluntly, we know that a thread needs a prerequisite when executing, that is, it needs to obtain the execution qualification of the system CPU. Although the thread has obtained the execution qualification, the CPU can also switch at any time, regardless of whether the thread has finished execution or not. Thread atomicity means that if a thread has been qualified to execute CPU, no thread can be interrupted if it has not finished executing.

In the following example, we demonstrate why the volatile keyword does not support thread atomicity.

We see that both the Thread-58 and the thread Thread-63 output count are 10000. This is obviously not true. The reason is that the volatile keyword does not support atomicity or synchronization. If we add the synchronized keyword to the count () method, the output is thread-safe.

Is it helpful for you to read the above content? If you want to know more about the relevant knowledge or read more related articles, please follow the industry information channel, thank you for your support.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report