-5
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 i = 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 is not affecting the output, it is only affecting If I have increased the sleep time.

Girish
  • 1,717
  • 1
  • 18
  • 30

1 Answers1

0

Marking stop volatile or not is not affecting the output, it is only affecting If I have increased the sleep time.

Not using volatile doesn't mean that threads sharing a same variable will always have a not updated value.

The idea is that according the case, it may and to prevent from having a not updated variable in one thread, you should declare the variable with the volatile modifier.

In your case, you don't see the problem as testThread has probably not run yet, so the value of the stop variable was not initialized yet in the memory of this thread.

Increasing the argument of sleep() allows the current thread to be paused.
testThread can so run and initialize the value of the variable to false in its own memory.
Then, the main thread is resumed and set stop to true :stop = true; so testThread doesn't see modification on stop.

davidxxx
  • 125,838
  • 23
  • 214
  • 215