Like System.out.println (count); do second thread see change in done ?
You are witnessing a side effect of println; your program suffers from a concurrent race condition. When coordinating data between the CPUs, it is important to tell the Java program that you want to share data between the CPUs, otherwise the CPUs may delay communication with each other.
There are several ways to do this in Java. The two main ones are “volatile” keywords and “synchronization”, which insert what the hardware guys call “memory barriers” into your code. Without the insertion of "memory barriers" into the code, the behavior of your parallel program is not defined. That is, we do not know when the "done" will become visible to another processor, and this, therefore, is a condition of the race.
Here is the implementation of System.out.println; pay attention to the use of synchronized. The synchronized keyword is responsible for placing memory barriers in the generated assembler, which has a side effect of making the variable “made” visible to another CPU.
public void println(boolean x) { synchronized (this) { print(x); newLine(); } }
The correct fix for your program is to read the read memory and write memory barrier when writing to it when reading. This is usually done by reading or writing “done” from a synchronized block. In this case, marking done as volatile will have the same network effect. You can also use AtomicBoolean instead of boolean for a variable.
source share