IllegalMonitorStateException mit zwei threads

Mein Programm hat zwei Threads, jeder druckt zehn zahlen. Der erste Thread, druckt die ungeraden Anzahl, der zweite Thread druckt die gerade Zahl ist, und Sie abwechselnd den Druck zahlen. Ich bin erwartet man eine Sequenz wie 1,2,3,4,5....bis 20, aber das Programm erzeugt eine IllegalMonitorStateException.

Ich weiß, was diese Exception bedeutet, aber ich benutze wait() und notify() im synchronisierten block. Hier ist mein 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 < 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 < 21; i += 2) {
                          synchronized (obj2) {

                          System.out.println(i + Thread.currentThread().getName());
                        try {
                            obj1.notify();
                            obj2.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }

            }.start();
        }
    }

- und das ist die Ausnahme generiert:

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)

Kann ich nicht verstehen. Irgendwelche Ideen?

InformationsquelleAutor Wei JingNing | 2012-03-01
Schreibe einen Kommentar