Your IllegalMonitorStateException exception is due to the fact that you must synchronize the object before calling wait or notify. So,
this.wait
should be
synchronized(this) { this.wait(); }
Your example will not run because you will never get to calling notify ... as soon as your thread gets on hold, it will be suspended and will not go any further. You must have two threads to wait / notify for work. One thread pauses when the wait method is called, and finally, the second thread calls synchronized(this) { this.notify() } to make the first thread wake up and continue executing under the wait call.
Synchronization is required because you usually check some condition before waiting, i.e.
synchronized(this) { if(! this.isReady) { this.wait(); } }
You need to synchronize to make sure that no other thread changes the state of the isReady flag between the line where you are checking the variable and the line you are waiting in. This way your notification code will be
synchronized(this) { isReady = true; this.notify(); }
Now the order of the method calls does not matter. If you first report this, no thread will wake up, but this is normal because you are not going to sleep, since isReady = true. If you go to bed first, isReady = true does nothing, but a notification call wakes up the thread. Finally, synchronization ensures that you do not check the variable in thread A, then set thread B and change the value (do nothing), then try thread A to sleep and never wake up.
Hope this helps.
source share