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.
undThrows: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 fordernthis.wait()
, so dass anstelle vonsynchronized (Object.class)
Sie tun müssensynchronized (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.
Du musst angemeldet sein, um einen Kommentar abzugeben.
Verwenden synchronized (this) { statt synchronisiert (Object.class) in Ihrer Klasse
BEARBEITEN
Argumentation hinter der IllegalMonitorException im obigen code
In Java mit synchronized-Schlüsselwort ist, eine Möglichkeit zu schaffen und zu erhalten, ein monitor-Objekt, das verwendet wird als Schleuse ausführen, der entsprechende code-block.
In dem obigen code, der monitor ist "Object.class".
Und wait () - Methode teilt den aktuellen thread warten, bis es notifyed und Sie zum aufrufen von wait() auf dem monitor-Objekt, das Eigentümer der Sperre.
Also auf dem Weg zum aufrufen von wait () - Methode ist wie folgt-sonst wird IllegalMonitorException.
Also für dein Beispiel, können Sie entweder
"Object.class.wait()"
oder ändern Sie den monitorthis
seit Sie anrufenwait()
Methode auf die aktuelle Instanzthis
. Methode wie wait, notify zu berufen, die synchronisierte Objekt.