title: Java threads in order
body: <p>I'm learning threads so I wanted to make a program which has two types of threads: one that writes random numbers and the other one which checks if the current number matches some specific number. The threads call write() and read(int) methods from the Numbers class. To make things more clear, I want my main program to look like this:</p>
  
  <pre><code>Numbers n = new Numbers();
  new WritingThread(n);
  new ReadingThread(n,3);
  new ReadingThread(n,5);
  </code></pre>
  
  <p>So the output would be something like this:</p>
  
  <pre><code>2 
  7
  3 !!! MATCH !!!
  8
  5 !!! MATCH !!!
  1
  ...
  </code></pre>
  
  <p>The thing is that threads are not executed in order. I want to first execute the WritingThread, and then all the ReadingThreads. Because this way a new random number would be written and only one thread would have the chance to check if the numbers match. Here is the code:</p>
  
  <p><strong>class Numbers</strong>:</p>
  
  <pre><code>public class Numbers {
  int number;
  boolean written = false;
  
  public synchronized void write() {
      while (written)
          try {
              wait();
          } catch (InterruptedException e1) {
              e1.printStackTrace();
          }
  
      number = (int) (Math.random() * 10);
      System.out.print("\n" + number);
      written = true;
      notifyAll();
  }
  
  public synchronized void check(int n) {
      while (!written)
          try {
              wait();
          } catch (InterruptedException e) {
              e.printStackTrace();
          }
      System.out.print(" Reading thread: "    + Thread.currentThread().getName());
      if (n == number) 
          System.out.print(" !!! MATCH !!! ");
      notify();
      written = false;
  }
  }
  </code></pre>
  
  <p><strong>class WritingThread</strong>:</p>
  
  <pre><code>public class WritingThread extends Thread {
      Numbers n;
      WritingThread(Numbers n){
          this.n = n;
          start();
      }
  
      public void run(){
          while(true){
              n.write();
          }
      }
  }
  </code></pre>
  
  <p><strong>class ReadingThread</strong>:</p>
  
  <pre><code>public class ReadingThread extends Thread{
  Numbers n;
  int number;
  public ReadingThread(Numbers n, int number){
      this.n = n;
      this.number = number;
      start();
  }
  
  public void run(){
      while(true){
          n.check(number);
      }
  }
  }
  </code></pre>
  
  <p>And the output:</p>
  
  <pre><code>3 Reading thread: Thread-2
  3 Reading thread: Thread-1 !!! MATCH !!! 
  0 Reading thread: Thread-2
  5 Reading thread: Thread-1
  0 Reading thread: Thread-2
  0 Reading thread: Thread-1
  5 Reading thread: Thread-2 !!! MATCH !!! 
  8 Reading thread: Thread-1
  </code></pre>
  
  <p>I know i could make one thread which has an array of numbers to check, but I am curious how could it be done this way. Thanks.</p>