title: synchronized method in for loop
body: <p>In the following simple example code (mainly taken from this <a href="https://www.udemy.com/java-multithreading/#/lecture/108950" rel="nofollow">nice udemy video</a>) there are two threads that increment a count instance variable through a <code>synchronized</code> method. </p>
  
  <p>This method however is inside a <code>for</code> loop in each thread.</p>
  
  <p>My question is: In a case like that, is it possible that the threads actually intermingle their calls to <code>increment</code>? For example something like:</p>
  
  <blockquote>
    <p>Thread 1 calls increment for i = 0 </p>
    
    <p>Thread 1 calls increment for i = 1 </p>
    
    <p>Thread 2 calls increment for j = 0 </p>
    
    <p>Thread 2 calls increment for j = 1 </p>
    
    <p>Thread 1 calls increment for i = 2 </p>
    
    <p>Thread 2 calls increment for j = 2 </p>
    
    <p>... and so on</p>
  </blockquote>
  
  <p>I tried running it many times for large <code>i</code>'s and <code>j</code>'s, but they always show sequentially, i.e. </p>
  
  <blockquote>
    <p>Thread 1 calls increment for i = 0 </p>
    
    <p>Thread 1 calls increment for i = 1 </p>
    
    <p>Thread 1 calls increment for i = 2 </p>
    
    <p>... Thread 1 finishes </p>
    
    <p>Thread 2 calls increment for j = 0 </p>
    
    <p>Thread 2 calls increment for j = 1 </p>
    
    <p>... Thread 2 finishes</p>
  </blockquote>
  
  <p>Based on my understanding on the <code>synchronized</code> keyword, the first case should happen, so I am just wondering if I am seeing the second case due to chance of there is something else that I am missing.</p>
  
  <pre><code> public class SyncTest {
  
      private int count = 0;
  
      public static void main(String[] args) {
          SyncTest test = new SyncTest ();
          test.doWork();
      }
  
      public synchronized void increment(String threadName) {
          System.out.println("thread: " + threadName);
          count++;
      }
  
      public void doWork() {
  
          Thread t1 = new Thread(new Runnable() {
              public void run() {
                  for (int i = 0; i &lt; 100000; i++) {
                      increment("t1");
                  }
              }
          });
  
          Thread t2 = new Thread(new Runnable() {
              public  void run() {
                  for (int j = 0; j &lt; 100000; j++) {
                      increment("t2");
                  }
              }
          });
  
          t1.start();
          t2.start();
  
          try {
              t1.join();
              t2.join();
          } catch(InterruptedException e) {
              e.printStackTrace();
          }
  
          System.out.println("Count is: " + count);
      }
  }
  </code></pre>