I've been thinking about it for almost the whole afternoon. Why this program its volatile variable almost couldn't approach 10000. Here is the code:
public class TestModifyVolatile {
volatile int count = 0;
void m(){
count++;
}
public static void main(String[] args) {
List<Thread> threads = new ArrayList<>();
TestModifyVolatile t = new TestModifyVolatile();
for (int i=0;i<10000;i++){
threads.add(new Thread(t::m,"t_"+i));
}
threads.parallelStream().forEach(e->e.start());
threads.forEach(o->{
try {
o.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
});
System.out.println(t.count);
}
}
Most of the result is 9996 9998... Assume thread 1 starts first, thread 1 made variable count turned to 1. In the process described above. Maybe another thread started at the same time as thread 1 that read variable count is also 0 and wrote back 1? That's my guess but i can not prove it