consider the following code
public class VolatileTester {
public static volatile int a = 0;
public static void main(String[] args) throws InterruptedException {
Thread t1 = new Thread() {
@Override
public void run() {
int d = 0;
while (d++ < 10000) {
a++;
}
}
};
Thread t2 = new Thread() {
@Override
public void run() {
int d = 0;
while (d++ < 10000) {
a++;
}
}
};
Thread t3 = new Thread() {
@Override
public void run() {
int d = 0;
while (d++ < 10000) {
a++;
}
}
};
t1.start();
t2.start();
t3.start();
t1.join();
t2.join();
t3.join();
System.out.println(a);
}
}
here as the variable a is volatile so I am expecting that the output should be 30000 but while running I am getting and in-deterministic answer which I will get anyway if the variable is not volatile.
so how volatile works is still remain unclear to me. can somebody put some light that where I am mistaken