volatile关键字能否保证线程安全?
Posted constxiong
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了volatile关键字能否保证线程安全?相关的知识,希望对你有一定的参考价值。
单纯使用 volatile 关键字是不能保证线程安全的
- volatile 只提供了一种弱的同步机制,用来确保将变量的更新操作通知到其他线程
- volatile 语义是禁用 CPU 缓存,直接从主内存读、写变量。表现为:更新 volatile 变量时,JMM 会把线程对应的本地内存中的共享变量值刷新到主内存中;读 volatile 变量时,JMM 会把线程对应的本地内存设置为无效,直接从主内存中读取共享变量
- 当把变量声明为 volatile 类型后,JVM 增加内存屏障,禁止 CPU 进行指令重排
- Java 自学指南
- Java 面试题汇总PC端浏览【点这里】
- Java知识图谱
- Java 面试题汇总小程序浏览,扫二维码
!--5f39ae17-8c62-4a45-bc43-b32064c9388a:W3siYmxvY2tJZCI6IjcwMjktMTU3MzExNjE4NTUzNSIsImJsb2NrVHlwZSI6InBhcmFncmFwaCIsInN0eWxlcyI6eyJhbGlnbiI6ImxlZnQiLCJpbmRlbnQiOjAsInRleHQtaW5kZW50IjowLCJsaW5lLWhlaWdodCI6MS43NSwiYmFjay1jb2xvciI6IiIsInBhZGRpbmciOiIifSwidHlwZSI6InBhcmFncmFwaCIsInJpY2hUZXh0Ijp7ImRhdGEiOlt7ImNoYXIiOiLljZUifSx7ImNoYXIiOiLnuq8ifSx7ImNoYXIiOiLkvb8ifSx7ImNoYXIiOiLnlKgifSx7ImNoYXIiOiIgIn0seyJjaGFyIjoidiJ9LHsiY2hhciI6Im8ifSx7ImNoYXIiOiJsIn0seyJjaGFyIjoiYSJ9LHsiY2hhciI6InQifSx7ImNoYXIiOiJpIn0seyJjaGFyIjoibCJ9LHsiY2hhciI6ImUifSx7ImNoYXIiOiIgIn0seyJjaGFyIjoi5YWzIn0seyJjaGFyIjoi6ZSuIn0seyJjaGFyIjoi5a2XIn0seyJjaGFyIjoi5pivIn0seyJjaGFyIjoi5LiNIn0seyJjaGFyIjoi6IO9In0seyJjaGFyI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yJjaGFyIjoiYSJ9LHsiY2hhciI6InQifSx7ImNoYXIiOiJpIn0seyJjaGFyIjoibCJ9LHsiY2hhciI6ImUifSx7ImNoYXIiOiIgIn0seyJjaGFyIjoi57G7In0seyJjaGFyIjoi5Z6LIn0seyJjaGFyIjoi5ZCOIn0seyJjaGFyIjoi77yMIn0seyJjaGFyIjoiSiJ9LHsiY2hhciI6IlYifSx7ImNoYXIiOiJNIn0seyJjaGFyIjoiICJ9LHsiY2hhciI6IuWiniJ9LHsiY2hhciI6IuWKoCJ9LHsiY2hhciI6IuWGhSJ9LHsiY2hhciI6IuWtmCJ9LHsiY2hhciI6IuWxjyJ9LHsiY2hhciI6IumanCJ9LHsiY2hhciI6Iu+8jCJ9LHsiY2hhciI6IuemgSJ9LHsiY2hhciI6IuatoiJ9LHsiY2hhciI6IiAifSx7ImNoYXIiOiJDIn0seyJjaGFyIjoiUCJ9LHsiY2hhciI6IlUifSx7ImNoYXIiOiIgIn0seyJjaGFyIjoi6L+bIn0seyJjaGFyIjoi6KGMIn0seyJjaGFyIjoi5oyHIn0seyJjaGFyIjoi5LukIn0seyJjaGFyIjoi6YeNIn0seyJjaGFyIjoi5o6SIn1dLCJpc1JpY2hUZXh0Ijp0cnVlLCJrZWVwTGluZUJyZWFrIjp0cnVlfX1d-->
以上是关于volatile关键字能否保证线程安全?的主要内容,如果未能解决你的问题,请参考以下文章