title: volatile keyword in java is not visible to other threads below is my code
body: <p>When I update the value of <code>i</code> in thread <code>T1</code>, the value is not visible to thread <code>T2</code> -  why?  Theoretically <code>volatile</code> variables must retrieve fresh values, but it is not working.</p>
  
  <pre><code>    class Threads implements Runnable
      {
  
        public volatile int i=4;
        volatile int j=0;
        int x=0;
  
        public static void main(String[] args) {
          Threads th=new Threads();
          Thread a = new Thread(th);
          Thread b=new Thread(th);
          a.setName("T1");
          a.setPriority(Thread.MAX_PRIORITY);
          b.setName("T2");
          a.start();
          b.start();
        }
  
        public int count() {
          return ++i;
        }
  
        public void run() {
          while(j&lt;=10)
          {
  
            if(Thread.currentThread().getName().equals("T1"))
            {
              i++;
              System.out.println(Thread.currentThread().getName()+" : "+i);
  
             try
             {
               Thread.sleep(2);
             }catch(Exception ex){}
           }
           else if(Thread.currentThread().getName().equals("T2"))
           {
  
             System.out.println(Thread.currentThread().getName()+" : "+i);
             try
             {
               Thread.sleep(1);
             }catch(Exception ex){}
           }
  
           j++;
         }
        }
      }
  </code></pre>