title: Java Thread Ping Pong example
body: <p>I'm trying to understand thread basics, and as a first example I create two thread that write a  String on the stdout. As I know the scheduler allows to execute the threads using a round robin schedule. Thats why I got:</p>
  
  <blockquote>
    <p>PING
    PING
    pong
    pong
    pong
    PING
    PING
    PING
    pong
    pong</p>
  </blockquote>
  
  <p>Now I want to use a shared variable, so every thread will know if its your turn:</p>
  
  <pre><code>public class PingPongThread extends Thread {
  private String msg;
  private static String turn;
  
  public PingPongThread(String msg){
      this.msg = msg;
  }
  @Override
  public void run() {
      while(true) {
          playTurn();
      }
  
  }
  public synchronized void playTurn(){
      if (!msg.equals(turn)){
          turn=msg;
          System.out.println(msg);
      }
  }
  }
  </code></pre>
  
  <p>Main class:</p>
  
  <pre><code>public class ThreadTest {
      public static void main(String[] args) {
          PingPongThread thread1 = new PingPongThread("PING");
          PingPongThread thread2 = new PingPongThread("pong");
          thread1.start();
          thread2.start();
      }
  }
  </code></pre>
  
  <p>I synchronized the "turn manager" but I still get something like:</p>
  
  <blockquote>
    <p>PING
    PING
    pong
    pong
    pong
    PING
    PING
    PING
    pong
    pong</p>
  </blockquote>
  
  <p><strong>Can someone explains what I am missing, and Why I'm not getting Ping pong... ping pong</strong>.
  Thanks!</p>