-2

I have this code :

public static void main(String[] args) throws InterruptedException {
    Object obj = new Object();

    obj.wait();
    obj.notify();

}

please I didn't understand why it throws java.lang.IllegalMonitorStateException??

user1703945
  • 79
  • 2
  • 8

1 Answers1

3

In order to wait on or notify on an object, you must be in a synchronized block locking on the object.

The following code will work (run but not do anything as there are no threads to synchronize):

public static void main(String[] args) throws InterruptedException {
    Object obj = new Object();
    synchronized(obj){
        obj.wait();
        obj.notify();
    }
}
Community
  • 1
  • 1
nanofarad
  • 40,330
  • 4
  • 86
  • 117