Java volatile修饰符和synchronized块
问题描述:
多个线程访问但仅在同步块内访问的变量是否需要volatile修饰符?如果没有,为什么?
Does a variable that is accessed by multiple threads, but only inside synchronized blocks, need the volatile modifier? If not, why?
答
您不需要使用 volatile
在$ code> synchronized 中,synchronized已经保证了在一致使用时(每次访问时)变量的本地缓存的正确行为。
You do not need to use volatile
inside of synchronized
, synchronized already guarantees the correct behavior for local caching of variables when used consistently (on every access).
volatile
适用于原始值,对于原始类型的原子访问可以是一个很好的快捷方式。请注意,volatile的行为在JDK 5中已从1.4更改。
volatile
works on primitive values, and can be a nice shortcut for atomic accesses to a primitive type. Note that the behavior of volatile has changed in JDK 5 from 1.4.
可以找到更多信息这里