title: Java Multithreading - How to print numbers in natural order
body: <p>I got it interview that:</p>
  
  <pre><code>Thread-A Prints Even numbers from 0
  Thread-B prints Odd numbers from 1
  </code></pre>
  
  <p>I want to print 0 1 2 3 4.... in natural order till 1000
  How can I achive.</p>
  
  <p>I tried this way: </p>
  
  <pre><code>public class ThreadDemo2 {
      static int aa = 0;
  
      public static void main(String[] args) {
          boolean mytime = true;
          EvenThread et = new EvenThread(mytime);
          OddThread ot = new OddThread(mytime);
          et.start();
          ot.start();
  
      }
  
  }
  
  class EvenThread extends Thread {
      boolean mytime;
      int i = 0;
  
      public EvenThread(boolean mytime) {
          this.mytime = mytime;
      }
  
      public void run() {
          //if (ThreadDemo2.aa == 0) {
              for (int i = 0; i &lt; 1000 &amp;&amp; ThreadDemo2.aa == 0; i += 2) {
                  System.out.println(i);
                  ThreadDemo2.aa = 1;
                  try {
                      sleep(500);
  
                  } catch (InterruptedException e) {
                      // TODO Auto-generated catch block
                      e.printStackTrace();
                  }
          //  }
  
          }/* else
              try {
                  this.wait();
              } catch (InterruptedException e) {
                  // TODO Auto-generated catch block
                  e.printStackTrace();
              }*/
      }
  
  }
  
  class OddThread extends Thread {
      boolean mytime;
      int i = 1;
  
      public OddThread(boolean mytime) {
          this.mytime = mytime;
      }
  
      public void run() {
          //if (ThreadDemo2.aa == 1) {
              for (int i = 1; i &lt; 1000 &amp;&amp; ThreadDemo2.aa == 1; i += 2) {
                  System.out.println(i);
                  ThreadDemo2.aa = 0;
                  try {
                      sleep(500);
                  } catch (InterruptedException e) {
                      // TODO Auto-generated catch block
                      e.printStackTrace();
                  }
              }
              //ThreadDemo2.aa = 0;
          //}
      }
  
  }
  </code></pre>