在一个线程中我有
write a = 0
write a = 1
write volatile flag = 1
在第二个线程中我有
read volatile flag // This always happens after I write volatile flag in thread 1
read a
是否可以进行重新排序,以便我看到在第二个线程中读取
返回 0?
如果不是,请有人详细解释一下原因吗?
我这么问是因为我对 JLS 的定义感到困惑:
Among all the inter-thread actions performed by each thread t, the program order of t is a total order that reflects the order in which these actions would be performed according to the intra-thread semantics of t.
在这种情况下似乎允许重新排序?
最佳答案
Can a reordering happen so I see read a returning 0 in the 2nd thread?
不,如果你的断言是正确的,“这总是发生在我在线程1中写入 volatile 标志之后”
线程 1 在更新 volatile 标志
之前对变量a
所做的最后一次更新将在线程 2 读取 volatile 标志后对线程 2 可见。
请参阅 Brian Goetz 的《Java 并发实践》第 3.1.4 节,了解更详细的解释:http://www.amazon.com/Java-Concurrency-Practice-Brian-Goetz/dp/0321349601
<小时/>但是请注意!依赖于 volatile 变量的读写来同步其他变量可能被认为是不好的做法。问题是,对于处理相同代码的其他程序员来说, volatile 变量和其他变量之间的关系可能并不明显。
关于java - Java中的 'program order'允许重新排序吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25549400/