I need clarification related to basic thread functionality and volatile method.In the given example:
public class ThreadDemo {
public static void main(String args[]){
Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
Priority_test hi=new Priority_test(Thread.NORM_PRIORITY+2);
hi.start();
try{
Thread.sleep(1000);
}catch(InterruptedException e){
System.out.println("Main thread interrupted");
}
hi.stop();
try{
hi.t.join();
}catch(InterruptedException e){
System.out.println("Interrupted");
}
System.out.println("High priority:"+hi.click);
}
}
public class Priority_test implements Runnable{
Thread t;
long click=0;
private volatile boolean running=true;
Priority_test(int p){
t=new Thread(this);
t.setPriority(p);
}
public void run(){
while(running)
click++;
}
public void start(){
t.start();
}
public void stop(){
running=false;
}
}
So,here 'hi' object is common to currentThread and child thread created inside 'hi'.That means both refer to same memory location....in that case if currentThread modifies value of variable 'running'(without using volatile) then it means value gets updated to the memory location from where child thread is reading its value.....but i guess something else is happening and my concept is not clear as without using volatile its going into infinite loop.Please explain how its happening internally.....i mean both threads are referring to same object and what difference does volatile make.I am really getting confused....:(