java - Unexpected Behaviour with and w/o Volatile Keyword -


public class threadvolatileperfectexample2 {   public static boolean  stop = false; // not volatile   public static void main(string args[]) throws interruptedexception {       thread testthread = new thread(){             @override             public void run(){               int = 1;               while(!stop){                   i++;               }               system.out.println("thread stop i="+ i);            }          };          testthread.start();          thread.sleep(1);          stop = true;          system.out.println("now, in main thread stop is: " + stop);          testthread.join();      }  } 

marking stop volatile or not not affecting output, affecting if have increased sleep time.

marking stop volatile or not not affecting output, affecting if have increased sleep time.

not using volatile doesn't mean threads sharing same variable have not updated value.

the idea according case, may , prevent having not updated variable in 1 thread, should declare variable volatile modifier.

in case, don't see problem testthread has not run yet, value of stop variable not initialized yet in memory of thread.

increasing argument of sleep() allows current thread paused.
testthread can run , initialize value of variable false in own memory.
then, main thread resumed , set stop true :stop = true; testthread doesn't see modification on stop.


Comments

Popular posts from this blog

ubuntu - PHP script to find files of certain extensions in a directory, returns populated array when run in browser, but empty array when run from terminal -

php - How can i create a user dashboard -

javascript - How to detect toggling of the fullscreen-toolbar in jQuery Mobile? -