I am trying to write a simple code to understand volatile keyword in java.
The idea is to increment the value of count field of Runner class using two threads. Helper class implements Runnable where run method increments the count which both static and volatile.
class Helper implements Runnable{
@Override
public void run() {
for(int i=0; i<100000;i++){
Runner.count+=1;
}
}
}
public class Runner {
public static volatile long count=0; // to be incremented
public static void main(String[] args){
Thread t1 = new Thread( new Helper());
Thread t2 = new Thread( new Helper());
t1.start();
t2.start();
try {
t1.join();
t2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Count= "+count); // output expected to be 200000
}
}
The expected output for every run is Count= 200000 , but sometimes i get a different number. Please help me understand how is that possible