Java Thread visibility problem. Why is there an infinite loop after adding output in threadA below? Isn't there a memory visibility problem? Why does the threadA get the latest flag in 1s?
public class Test {
private static boolean flag = true;
public static void main(String[] args) throws InterruptedException {
new Thread(() -> {
while (flag) {
//If you don't add this sout, it will be an infinite loop,
//and if you add it, it will not be an infinite loop.
System.out.println("loop");
}
System.out.println("end");
},"threadA").start();
TimeUnit.MILLISECONDS.sleep(1000);
flag = false;
}
}