I have a simple TestThreadClientMode
class to test a race condition. I tried two attempts:
- When I run the following code with
System.out.println(count);
commented in the second thread, the output was:
OS: Windows 8.1
flag done set true
...
and the second thread was alive forever. Because the second thread never sees change of the done
flag which was set true by Main thread.
When I uncommented
System.out.println(count);
the output was:OS: Windows 8.1 0 ... 190785 190786 flag done set true Done! Thread-0 true
And the program stopped after 1 second.
How did System.out.println(count);
make the second thread see the change in done
?
Code
public class TestThreadClientMode {
private static boolean done;
public static void main(String[] args) throws InterruptedException {
new Thread(new Runnable() {
public void run() {
int count = 0;
while (!done) {
count ++;
//System.out.println(count);
}
System.out.println("Done! " + Thread.currentThread().getName() + " " + done);
}
}).start();
System.out.println("OS: " + System.getProperty("os.name"));
Thread.sleep(1000);
done = true;
System.out.println("flag done set true ");
}
}