Warum Java throw von java.lang.IllegalMonitorStateException, wenn ich rufe wait() in statischer Weise synchronisiert block?

Verstehe ich nicht, warum Java-Ausnahme ausgegeben vom Thema in diesem code. Könnte jemand mir erklären es?

class Wait implements Runnable
{
    public void run() {
        synchronized (Object.class) {
            try {
                while(true) {
                    System.out.println("Before wait()");
                    wait();
                    System.out.println("After wait()");
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

public class ObjectMethodInConcurency 
{
    public static void main(String[] args) {
        Wait w = new Wait();
        (new Thread(w)).start();
    }
}
  • Lesen Sie die javadoc für wait().
  • The current thread must own this object's monitor. und Throws:IllegalMonitorStateException - if the current thread is not the owner of the object's monitor.
  • Man kann Sie nur anrufen wait() auf ein Objekt, das Sie haben, synchronisiert. Sie fordern this.wait(), so dass anstelle von synchronized (Object.class) Sie tun müssen synchronized (this). Object.class ist nicht Ihr Objekt, es ist ein java.lang.Class -Objekt erstellt, indem der Java-runtime.
  • Sie nicht ruft " notify() überall.
  • Danke für die Informationen. Ich änderte den Aufruf der Methode auf Object.class.wait() und es funktioniert wie ich es will.
InformationsquelleAutor koralgooll | 2014-01-15
Schreibe einen Kommentar