title: getting wrong value when using volatile keyword in java
body: <p>I have doubt in the behaviour of volatile keyword.</p>
  
  <pre><code>public class TestClassI extends Thread {
  
      private volatile int i=5;
      boolean flag;
      public TestClassI( boolean flag) {
          this.i=i;
          this.flag=flag;
      }   
      public void run()
      {
          if(flag)
          {
              while(true)
              {
                  System.out.println(i);
                  try {
                      Thread.sleep(1000);
                  } catch (InterruptedException e) {
                      // TODO Auto-generated catch block
                      e.printStackTrace();
                  }
              }
          }
          else
          {
              i=10;
          }
      }
  }
  </code></pre>
  
  <p>and in main class using as</p>
  
  <pre><code>public class TestMain {
  
      public static volatile int i=5;
      public static void main(String args[]) throws InterruptedException
      {
  
          TestClassI test= new TestClassI( true);
          test.start();
          Thread.sleep(1000);
  
          TestClassI test2=new TestClassI( false);        
          test2.start();
      }
  }
  </code></pre>
  
  <p>I expected the value will be like
  5
  5
  5
  5
  10
  10
  10
  10.
  But it is keep on giving 5. But asper nature of volatile value of i should be stored and retrieved from main memory each time. Please explain is there anything wrong in this code?</p>