I'm trying to understand working of volatile variable. I have created a simple class "A" which extends "Thread" and has a volatile variable "i". There's another class "Amain" that runs 3 threads of class "A". I'm running a loop inside run() of A which depends on this volatile variable. Here the code.
// Thread
public class A extends Thread {
public volatile int i = 0;
@Override
public void run() {
while(i<10)
System.out.println(i++ + " " + this.getName());
}
}
// Main Class
public class Amain {
public static void main(String[] args) {
A t1 = new A();
A t2 = new A();
A t3 = new A();
t1.start();
t2.start();
t3.start();
}
}
If the volatile value is shared among all threads then "i" should have been printed 10 times. Instead its printing 10 values for each thread i.e a total of 30 values. Need to understand working of volatile in context of this code. Also what can I do to get only 10 values of i from any number of threads(in context of this code).