I am trying to understand the volatile
keyword and wrote a dummy program to test it.
public class SharedObjects {
public static void main(String[] args) {
MyRunnable runnable = new MyRunnable();
Thread thread1 = new Thread(runnable, "Thread 1");
Thread thread2 = new Thread(runnable, "Thread 2");
thread1.start();
thread2.start();
System.out.printf("%s: %d\n", Thread.currentThread().getName(), runnable.count);
}
}
public class MyRunnable implements Runnable {
public volatile int count = 0;
@Override
public void run() {
for (int i = 0; i < 1000000; i++) {
count++;
}
System.out.printf("%s: %d\n", Thread.currentThread().getName(), count);
}
}
Output:
main: 1024
Thread 2: 831910
Thread 1: 902879
I think with or without volatile
keyword, the result of the last finished thread should be at least 1000000 (the number of times of the loop), but it doesn't with volatile
keyword.
If I remove the volatile
keyword, it always gives a number at least 1000000, like
main: 1063
Thread 2: 1086742
Thread 1: 1086742