java - Java中的 'program order'允许重新排序吗?

标签 java multithreading volatile jls

在一个线程中我有

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/

相关文章:

Java Swing BasicUI 更新错误,我该怎么办?

c++ - 使用 clang 对 std::atomic 函数的调用不明确

java - 在另一台服务器上调用 ColdFusion 函数?

java - SQL 的 CURRENT_TIMESTAMP(通过 JDBC 使用时)与时区无关吗?

java - 为什么 JSONArray 不提供 contains() 方法?

java - 为什么@Qualifier 不允许在构造函数之上?

c - C中pthread_join()的返回顺序

c++ - 关于 boost::lock_guard 和 boost::unique_lock

c++ - C++ 编译器能否消除未读取的 volatile 局部变量

c - 未使用的 volatile 变量