title: Why is Java synchronized not working as expected?
body: <p>I'm trying to figure out how synchronized methods work. From my understanding I created two threads <strong>T1</strong> and <strong>T2</strong> that will call the same method <code>addNew</code>, since the method is synchronized shouldn't it execute all the iterations of the for loop for one thread and then the other? The output keeps varying, sometimes it prints it right, other times it prints values from T1 mixed with T2 values. The code is very simple, can someone point out what am I doing wrong? Thank you.</p>
  
  <pre><code>public class Main {
      public static void main(String[] args) {
          Thread t1 = new Thread(new A());
          Thread t2 = new Thread(new A());
          t1.setName("T1");
          t2.setName("T2");
          t1.start();
          t2.start();
      }
  }
  
  public class B {
      public synchronized void addNew(int i){
          Thread t = Thread.currentThread();
          for (int j = 0; j &lt; 5; j++) {
              System.out.println(t.getName() +"-"+(j+i));
          }
      }
  }
  
  public class A extends Thread {
      private B b1 = new B();
  
      @Override
      public void run() {
          b1.addNew(100);
      }
  }
  </code></pre>