I am reading Effective Java of J. Bloch, and in concurrency chapter there is one example:
public class Main {
private static boolean stop;
public static void main(String[] args) throws InterruptedException {
new Thread(() -> {
int i = 0;
while (!stop) {
i++;
}
}).start();
TimeUnit.SECONDS.sleep(1);
stop = true;
}
}
This example shows that without synchronization child thread won't stop, because it can't see changes made by main thread. But if we change code to this:
public class Main {
private static boolean stop;
public static void main(String[] args) throws InterruptedException {
new Thread(() -> {
while (!stop) {
System.out.println(i);
}
}).start();
TimeUnit.SECONDS.sleep(1);
stop = true;
}
}
application will stop after 1 second. So could someone explain why System.out.println
synchronizes threads unlike the first variant doesn't?