I need some example on Volatile Keyword of Java Threads.
As per definition of volatile keyword it says, when variable is declared as volatile then thread will directly read/write to variable memory instead of read/write from local thread cache.
please correct me if I am wrong.
So in that understanding when I run the below program,
public class ThreadRunnableBoth implements Runnable{
private volatile int num =0;
public void run(){
Thread t = Thread.currentThread();
String name = t.getName();
for(int i=0; i<100; i++){
if(name.equals("Thread1")){
num=10;
System.out.println("value of num 1 is :"+num);
}else{
num=15;
System.out.println("value of num 2 is :"+num);
}
}
}
public static void main(String args[]) throws InterruptedException{
Runnable r = new ThreadRunnableBoth();
Thread t1 = new Thread(r);
t1.setName("Thread1");
Thread t2 = new Thread(r);
t2.setName("Thread2");
t1.start();
t2.start();
}
}
I got these example from some site and when i tried running it I cant see any difference removing Volatile or adding Volatile Keyword.
Please explain me the difference happens on removing it and adding it.
Thanks a lot.