Volatile in Java cannot guarantee thread safety (example explanation)
•
Java
Today, I typed the code to study whether the volatile keyword of Java can ensure thread safety. After practice, volatile can not ensure thread safety. It only ensures the visibility of data and will not be cached. Each thread reads data from main memory rather than from cache. The attached code is as follows. When synchronized is removed, The result of each thread is chaotic, and the result is correct when it is added.
The above article that volatile in Java can not guarantee thread safety (example explanation) is all the content shared by Xiaobian. I hope it can give you a reference and support more programming tips.
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码