怎么随便进一个都是各种不到点上的……
根本原因是 Java 语言不保证这里的调度公平性,所以明确允许把你 = true 饿死了不管。
这玩意儿跟可见性看起来表面上是有点关系,但不巧,Java 里这条恰恰是单独拎出来授权的:
https://docs.oracle.com/javase/specs/jls/se16/html/jls-17.html#jls-17.4.9
Programs can hang if all threads are blocked or if the program can perform an unbounded number of actions without performing any external actions.
这样设计的理由,在 JSR-133 Chapter 13 里有提,是个妥协:
https://www.cs.umd.edu/~pugh/java/memoryModel/jsr133.pdf
(老实说这样设计挺欠扁的,虽然还有人居然认为这个“容易理解”: https://stefansf.de/post/non-termination-considered-harmful/ ←注意这人说的 C 和 C++ 在这里 undefined behavior 这个明确是错的。)
@az467 你确定这问题真经?
和你说的恰恰相反,除了 JVM 自己高兴是不是愿意这样搞,这跟 JVM 没有半点关系。
关掉 JIT 也不保证一定顶用。
@ipwx C++ 和这个明显不一样。
C++ 是明确允许 forward prograss,反面允许把整个 while 直接优化没掉而不是 blocking:
C++17 § 4.7.2 Forward progress ¶ 1
The implementation may assume that any thread will eventually do one of the following:
– terminate,
– make a call to a library I/O function,
– perform an access through a volatile glvalue, or
– perform a synchronization operation or an atomic operation.
[Note: This is intended to allow compiler transformations such as removal of empty loops, even when termination cannot be proven. — end note]
虽然只是允许,所以实现上可能刚好一样……
另外注意 C++ 这里是每线程内的约束。Java 的 volatile 自 JDK 1.4 后跟 C++11 的 std::atomic 语义类似,但这里 C++ 可是 volatile 就够了。