title: Java - Two threads communicating via wait()/notify() but threads are alternating on with thread gets lock first
body: <p>The desired output of this programme is:</p>
  
  <p>Ping
  Pong
  Ping
  Pong
  Ping
  Pong</p>
  
  <p>Yet it alternates between that and</p>
  
  <p>Pong
  Ping 
  etc.</p>
  
  <p>The thing is, I create the Ping thread and run it first. So I am not sure why Pong is occassionally coming first.</p>
  
  <p>So here is my code (readily compilable). It works, essentially. I just don't understand why it sometimes prints "Pong" first. Could someone please shed some light as to why this is happening?</p>
  
  <pre><code>// Printer class - will be the object that both threads lock / synchronize onto
  class Printer
  {
      int numberOfMessages;
      int messageCount;
  
      // Constructor allowing user to choose how many messages are displayed
      Printer(int numberOfMessages)
      {       
          this.numberOfMessages = numberOfMessages;
          this.messageCount = 0;
      }
  
      // If more messages are to be printed, print and increment messageCount
      void printMsg(String msg)
      {
          if (messageCount &lt; numberOfMessages)
          {
              System.out.println("[" + msg + "]");            
              ++messageCount;
          }
          else
          {
              System.exit(0);
          }
      }
  }
  
  // PingPong thread
  class PingPongThread extends Thread
  {
      Printer printer;
      String message; 
  
      public PingPongThread(Printer printer, String message)
      {
          this.printer = printer;
          this.message = message;
          this.start();
      }
  
      @Override
      public void run()
      {
          while(true)
          {
              synchronized (printer)
              {                   
                  // Print message whether it is Ping or Pong
                  printer.printMsg(message);
  
                  // Notify
                  printer.notify();
  
                  // Wait
                  try
                  {
                      printer.wait();
                  } 
                  catch (InterruptedException e)
                  {               
                      e.printStackTrace();
                  }
              }
          }
      }
  
  
  }
  
  // Two threads communicate with eachother to alteratively print out "Ping" and "Pong"
  public class PingPong
  {
      public static void main(String args[])
      {
          Printer printer = new Printer(6);
  
          PingPongThread pingThread = new PingPongThread(printer, "Ping");
          PingPongThread pongThread = new PingPongThread(printer, "Pong");
      }
  }
  </code></pre>