In continuation with this article. Could someone please explain why does one of the below code snippet demonstrates the visibility problem (Thread keeps running forever) while the other does not on the same windows 64 bit machine.
Note: I suspect that it could have something to do with println method of PrintStream class in System class being synchronized. Could someone explain the same. How does it impact the visibility.
Code snippet 1 - Demos visibility problem (Thread t1 keeps running as expected)
public class Test2 extends Thread {
boolean keepRunning = true;
public static void main(String[] args) throws InterruptedException {
Test2 t = new Test2();
t.start();
Thread.sleep(1000);
t.keepRunning = false;
System.out.println(System.currentTimeMillis() + ": keepRunning is false");
}
public void run() {
while (keepRunning)
{}
}
}
Code snippet 2 - Does not demo visibility problem (Thread t1 stops running which is not expected)
public class Test2 extends Thread {
boolean keepRunning = true;
public static void main(String[] args) throws InterruptedException {
Test2 t = new Test2();
t.start();
Thread.sleep(1000);
t.keepRunning = false;
System.out.println(System.currentTimeMillis() + ": keepRunning is false");
}
public void run() {
int count = 0;
while (keepRunning)
{
System.out.println(count++);
}
}
}