I'm testing the memory consistency
function of the volatile
keyword.
This is code that does NOT use volatile, the program will be stuck as expected.
package cn.demojie.singleton;
public class VolatileTest2 {
private static boolean flag = false;
public static void main(String[] args) throws Exception {
new Thread(
() -> {
while (!flag) {
/* Uncomment it, the program won't get stuck anymore
try {
Thread.sleep(0);
} catch (InterruptedException e) {
e.printStackTrace();
}
*/
}
})
.start();
Thread.sleep(50);
flag = true;
}
}
But when I add Thread.sleep()
like the comments above, the program won't get stuck anymore.
It seems the memory consistency is in effect. Why?
System.out.println()
also works as the Thread.sleep()