title: Difference in thread behaviour while accessing variable
body: <p>I was going through the tutorial <a href="https://www.youtube.com/watch?v=SC2jXxOPe5E" rel="nofollow noreferrer">https://www.youtube.com/watch?v=SC2jXxOPe5E</a> to understand how volatile variable works and came across a strange behavior.</p>
  
  <p>For the following code snippet </p>
  
  <pre><code>public class VolatileDemo {
      static boolean running = false;
      public static void main(String a[]) throws InterruptedException {
          Thread t = new Thread(new Runnable() {
              @Override
              public void run() {
                  while (!running) {
                  }
                  System.out.print("Started");
                  while (running) {
                  }
                  System.out.print("Stopped");
              }
          });
          t.start();
          Thread.sleep(1000);
          running = true;
          System.out.print("Starting ");
          Thread.sleep(1000);
          running = false;
          System.out.print("Stopping");
      }
  }
  </code></pre>
  
  <p>The output is : Starting Stopping (which is understandable by video)</p>
  
  <p>But for the following code snippet</p>
  
  <pre><code>public class VolatileDemo {
      static boolean running = false;
      public static void main(String a[]) throws InterruptedException {
          Thread t = new Thread(new Runnable() {
              @Override
              public void run() {
                  while (!running) {
                      System.out.print("Flag " + running);
                  }
                  System.out.print(" Started");
                  while (running) {
                      System.out.print(" Flag " + running);
                  }
                  System.out.print(" Stopped");
              }
          });
          t.start();
          Thread.sleep(1000);
          running = true;
          System.out.print(" Starting");
          Thread.sleep(1000);
          running = false;
          System.out.print(" Stopping");
      }
  }
  </code></pre>
  
  <p>The output is Flag: false Starting Started Flag: true Stopping Stopped(ignore the output)</p>
  
  <p>My concern here is why the thread was able to read the updated value of '<em>running</em>' in case 2?</p>
  
  <p>Edit: The difference between the two snippets is the addition below statement in later case</p>
  
  <pre><code>System.out.print("Flag " + running);
  </code></pre>