title: Thread Synchronization - Synchronizing three threads to print 012012012012..... not working
body: <p>I am trying to synchronize three threads to print 012012012012.... but it is not working correctly. Each thread is assigned a number which it prints when it receives a signal from main thread. There is something wrong with the following program which I am not able to catch. </p>
  
  <pre><code>public class Application {
      public static void main(String[] args) {
  
          int totalThreads = 3;
          Thread[] threads = new Thread[totalThreads];
  
          for (int i = 0; i &lt; threads.length; i++) {
              threads[i] = new MyThread(i);
              threads[i].start();
          }
  
          int threadIndex = 0;
          while (true) {
              synchronized(threads[threadIndex]) {
                  threads[threadIndex].notify();
              }
  
              threadIndex++;
              if (threadIndex == totalThreads) {
                  threadIndex = 0;
              }
          }
      }
  }
  
  class MyThread extends Thread {
      private int i;
  
      public MyThread(int i) {
          this.i = i;
      }
  
      @Override
      public void run() {
          while (true) {
              synchronized(this) {
                  waitForSignal();
                  System.out.println(i);
              }
          }
      }
  
      private void waitForSignal() {
          try {
              wait();
          } catch (InterruptedException e) {
              e.printStackTrace();
          }
      }
  }
  </code></pre>