I am learning volatile variable. I know what volatile does, i wrote a sample program for Volatile variable but not working as expected.
Why is the final value of the "count" coming sometime less then 2000. I have used volatile hence the system should not cache "count" variable and the value should always be 2000.
When I used synchronized method it work fine but not in the case of volatile keyword.
public class Worker {
private volatile int count = 0;
private int limit = 10000;
public static void main(String[] args) {
Worker worker = new Worker();
worker.doWork();
}
public void doWork() {
Thread thread1 = new Thread(new Runnable() {
public void run() {
for (int i = 0; i < limit; i++) {
count++;
}
}
});
thread1.start();
Thread thread2 = new Thread(new Runnable() {
public void run() {
for (int i = 0; i < limit; i++) {
count++;
}
}
});
thread2.start();
try {
thread1.join();
thread2.join();
} catch (InterruptedException ignored) {}
System.out.println("Count is: " + count);
}
}
Thank You in advance !