I do not understand why Java throw exception from subject in this code. Could somebody explain me it?
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();
}
}
wait()
.The current thread must own this object's monitor.
andThrows:IllegalMonitorStateException - if the current thread is not the owner of the object's monitor.
wait()
on an object which you have synchronized on. You are callingthis.wait()
, so instead ofsynchronized (Object.class)
, you must dosynchronized (this)
. Object.class is not your object, it is a java.lang.Class object created by the Java runtime.Object.class.wait()
and it works like I want.