In java specification 17.3. Sleep and Yield, it says
It is important to note that neither Thread.sleep nor Thread.yield have any synchronization semantics.
This sentence is the point. If I replace Thread.sleep(100)
by System.out.println("")
in my test code below, the compiler always read iv.stop
every time because System.out.println("")
acquires a lock, check this question. Java specification says Thread.sleep
does not have any synchronization semantics, so I wonder what makes compiler treat Thread.sleep(100)
as same as System.out.println("")
.
My test code:
public class InfiniteLoop {
boolean stop = false;
public static void main(String[] args) throws InterruptedException {
final InfiniteLoop iv = new InfiniteLoop();
Thread t1 = new Thread(() -> {
while (!iv.stop) {
//uncomment this block of code, loop broken
// try {
// Thread.sleep(100);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
}
System.out.println("done");
});
Thread t2 = new Thread(() -> {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
iv.stop = true;
});
t1.start();
t2.start();
}
}
As the comment above says, Thread.sleep()
breaks the loop, this is different from the description of the Java specification: why?