Java volatile修饰符和synchronized块 [英] Java volatile modifier and synchronized blocks

查看:104
本文介绍了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.

可以找到更多信息这里

这篇关于Java volatile修饰符和synchronized块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆