title: Java Thread Synchronization 101
body: <p>Thinking that the shared object <code>Control</code> would enforce that <code>n</code> threads (<code>Number</code>) display in order, they clearly do not:</p>
  
  <p>Number:</p>
  
  <pre><code>public class Number implements Runnable {
  
      private int i_;
      private Control control;
  
      public Number(int i, Control c) {
          i_ = i;
          control = c;
      }
  
      public void start() {
          new Thread(this).start();
      }
  
      public void run() {
          synchronized(control) {
              control.call(i_);
          }
      }
  }
  </code></pre>
  
  <p>Control:</p>
  
  <pre><code>public class Control {
  
      private int i_ = 0;
  
      public void call(int i) {
  
          if(i != i_) {
              try {
                  wait();
              }
              catch(Exception e) {}
          }
  
          System.out.println(i);
          i_++; // next, please                                                                                                                                                                                   
          notify();
      }
  }
  </code></pre>
  
  <p>Test harness (main):</p>
  
  <pre><code>public class RunNumbers {
  
      public static void main(String args[]) {
  
          int n = 0;
          if (args.length &gt; 0) {
              n = Integer.parseInt(args[0]);
          }
  
          Control c = new Control();
          for(int i = 0; i &lt; n; ++i) {
              new Number(i, c).start();
          }
      }
  }
  
  </code></pre>
  
  <p>Any ideas?</p>