title: Java Multi-Threading unexpected result
body: <p>I have a simple Java program with 3 threads, each incrementing and then printing a variable <code>counter</code>. The java code is- </p>
  
  <pre><code>public class test implements Runnable {
  
      private int counter=0;
  
      public static void main(String args[]){
  
          test t=new test();
          Thread t1=new Thread(t,"THREAD 1");
          Thread t2=new Thread(t,"THREAD 2");
          Thread t3=new Thread(t,"THREAD 3");
          t1.start();
          t2.start();
          t3.start();
  
      }
  
      public  void run(){
  
          counter=counter+1;
              System.out.println(Thread.currentThread().getName()+" "+ counter);
  
      }
  }
  </code></pre>
  
  <p><br>Understanding that the method <code>run</code> is not synchronized the threads can interleave in any fashion giving any result but the result I get mostly(I've run the program multiple times) is- </p>
  
  <pre><code>THREAD 1 2
  THREAD 3 3
  THREAD 2 2
  </code></pre>
  
  <p><br>
  I don't understand how come <code>1</code> is never printed and even after printing <code>3</code>, <code>2</code> is again printed(since the most recent value of <code>counter</code> has been set to <code>3</code>, as it is printed).<br><br>
  Also, is the variable <code>counter</code> shared among the 3 threads? It will be shared if I make it <code>static</code> but what in this case.<br>
  Please explain.</p>