关于 volatile

2022-12-03 20:59:34 +08:00
 wangyu17455

不知道为什么有这么多人在测试 volatile 的作用的时候喜欢用 println 这个方法,然后因为 println 方法的特殊性就得出一个结论,volatile 其实加和不加都一样。 首先,println 内部有 synchronized ,它的特殊性指的就是这一点。这会导致缓存失效,进而导致变量的重新读取,无论加没加 volatile 。

while(aBoolean){
	System.out.println("running");
}

上面这种方式检验 volatile 是绝对错误的! 正确的方式是

while(aBoolean){}
System.out.println("done");

这将导致线程永远空转,而加了 volatile 之后就可以正确的输出 done

912 次点击
所在节点    Java
2 条回复
L4Linux
2022-12-04 01:25:15 +08:00
println 的 synchronized 只保证输出的原子性吧,管得着方法外的变量吗?你不妨举例说说其它 threads 有怎样的代码。
wangyu17455
2022-12-04 02:12:01 +08:00
@L4Linux
Concurrent Programming in Java 里说了啊
In essence, releasing a lock forces a flush of all writes from working memory employed by the thread, and acquiring a lock forces a (re)load of the values of accessible fields. While lock actions provide exclusion only for the operations performed within a synchronized method or block, these memory effects are defined to cover all fields used by the thread performing the action.
是当前作用域的所有变量都 reload from memory

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/899871

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX