According to the Java Language Specification, §17.3, "Sleep and Yield" [JLS 2011],
It is important to note that neither
Thread.sleep
norThread.yield
have any synchronization semantics. In particular, the compiler does not have to flush writes cached in registers out to shared memory before a call toThread.sleep
orThread.yield
, nor does the compiler have to reload values cached in registers after a call toThread.sleep
orThread.yield
.
...
However, the compiler is free to read the field this.done
once and to reuse the cached value in each execution of the loop. Consequently, the while
loop might never terminate, even when another thread calls the shutdown()
method to change the value of this.done
[JLS 2011]. This error could have resulted from the programmer incorrectly assuming that the call to Thread.sleep()
would cause cached values to be reloaded.
...
Relying on the Thread
class's sleep()
, yield()
, and getState()
methods for synchronization control can cause unexpected behavior.
Related Guidelines
Bibliography
...