title: Synchronization multithreading in java
body: <p>I'm self-learning Java and I want to understand multithreading. I created <code>MyThread</code> class with a job to perform a loop until a condition is true and then print information about it. It contains static field <code>left</code> which is incremented in a constructor and decremented when a job is done. Class <code>Flag</code> is 'telling' threads when to start.
  Unfortunately, when all threads are done <code>left</code> does not equal zero. I made some of methods <code>synchronized</code> and it got better but it still is not perfect.
  What am I doing wrong?</p>
  
  <pre><code>import java.util.Random;
  
  class Flag
  {
      private boolean ok = false;
      synchronized boolean ok()
      {
          return ok;
      }
      synchronized void setOk(boolean ok)
      {
          this.ok = ok;
      }
  }
  
  class MyThread extends Thread
  {
      static int left = 0;
  
      synchronized void add()
      {
          left++;
      }
  
      synchronized int remove()
      {
          return --left;
      }
  
      String name;
      Flag flag;
      Random rnd = new Random();
      public MyThread(String name, Flag flag)
      {
          this.name = name;
          this.flag = flag;
          add();
      }
  
      public void run()
      {
          while(!flag.ok());
  
          double rnd;
          long count = 0;
          do{
              count++;
              rnd = Math.random();
          } while(rnd &gt; 0.00001);
          print(count);
      }
  
      synchronized void print(long count)
      {
          System.out.printf("%s %10d left: %3d%n", name, count, remove());
      }
  }
  
  public class Test
  {
      public static void main(String... args) throws Exception
      {
          Flag flag = new Flag();
          for(int i=0; i&lt;2000; i++){
              new MyThread(String.format("%04d",i),flag).start();
          }
  
          flag.setOk(true);
      }
  }
  </code></pre>