title: Sharing variable between threads in JAVA
body: <p>I have two threads doing calculation on a common variable "n", one thread increase "n" each time, another decrease "n" each time, when I am not using volatile keyword on this variable, something I cannot understand happens, sb there please help explain, the snippet is like follow:</p>
  
  <pre><code>public class TwoThreads {
  
  private static int n = 0;
  private static int called = 0;
  
  public static void main(String[] args) {
  
      for (int i = 0; i &lt; 1000; i++) {
          n = 0;
          called = 0;
  
          TwoThreads two = new TwoThreads();
          Inc inc = two.new Inc();
          Dec dec = two.new Dec();
          Thread t = new Thread(inc);
          t.start();
          t = new Thread(dec);
          t.start();
          while (called != 2) {
              //System.out.println("----");
          }
          System.out.println(n);
  
      }
  }
  
  private synchronized void inc() {
      n++;
      called++;
  }
  
  private synchronized void dec() {
      n--;
      called++;
  }
  
  class Inc implements Runnable {
      @Override
      public void run() {
          inc();
      }
  }
  
  class Dec implements Runnable {
      @Override
      public void run() {
          dec();
      }
  }
  </code></pre>
  
  <p>}</p>
  
  <p>1) What I am expecting is "n=0,called=2" after execution, but chances are the main thread can be blocked in the while loop;</p>
  
  <p>2) But when I uncomment this line, the program when as expected:</p>
  
  <pre><code>//System.out.println("----");
  </code></pre>
  
  <p>3) I know I should use "volatile" on "called", but I cannot explain why the above happens;</p>
  
  <p>4) "called" is "read and load" in working memory of specific thread, but why it's not "store and write" back into main thread after "long" while loop, if it's not,  why a simple "print" line can make such a difference</p>