title: IllegalMonitorStateException with two threads
body: <p>My program has two Threads, each prints ten numbers. The first Thread prints the odd number, the second Thread prints the even number, and they take turns printing numbers. I'm expecting to get a sequence like 1,2,3,4,5....until 20, but the program produces an IllegalMonitorStateException.</p>
  
  <p>I know what this Exception means, but I use <code>wait()</code> and <code>notify()</code> in the synchronized block. Here is my code:</p>
  
  <pre><code>     public class EvenOddThreadTest {
  
        /**
         * @param args
         */
        static Object obj1 = new Object();
        static Object obj2 = new Object();
        static Object obj3=new EvenOddThreadTest();
  
        public static void main(String[] args) throws InterruptedException {
            new Thread() {
                @Override
                public void run() {
  
                        for (int i = 1; i &lt; 21; i += 2) {
                            synchronized (obj1) {
                            System.out.println(i + Thread.currentThread().getName());
                            try {
                                obj2.notify();                    
                                obj1.wait();
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
  
                        }
                    }
                }
            }.start();
            new Thread() {
                @Override
                public void run() {
                        for (int i = 2; i &lt; 21; i += 2) {
                            synchronized (obj2) {
  
                            System.out.println(i + Thread.currentThread().getName());
                          try {
                              obj1.notify();
                              obj2.wait();
                          } catch (InterruptedException e) {
                              e.printStackTrace();
                          }
                      }
                  }
              }
  
              }.start();
          }
      }
  </code></pre>
  
  <p>and this is the Exception generated:</p>
  
  <pre><code>1Thread-0
  2Thread-1
  Exception in thread "Thread-0" java.lang.IllegalMonitorStateException
      at java.lang.Object.notify(Native Method)
      at EvenOddThreadTest$1.run(EvenOddThreadTest.java:21)
  Exception in thread "Thread-1" java.lang.IllegalMonitorStateException
      at java.lang.Object.notify(Native Method)
      at EvenOddThreadTest$2.run(EvenOddThreadTest.java:41)
  </code></pre>
  
  <p>I can't figure this out. Any ideas?</p>