How to use wait and notify in Java without IllegalMonitorStateException? How to use wait and notify in Java without IllegalMonitorStateException? multithreading multithreading

How to use wait and notify in Java without IllegalMonitorStateException?


To be able to call notify() you need to synchronize on the same object.

synchronized (someObject) {    someObject.wait();}/* different thread / object */synchronized (someObject) {    someObject.notify();}


While using the wait and notify or notifyAll methods in Java the following things must be remembered:

  1. Use notifyAll instead of notify if you expect that more than one thread will be waiting for a lock.
  2. The wait and notify methods must be called in a synchronized context. See the link for a more detailed explanation.
  3. Always call the wait() method in a loop because if multiple threads are waiting for a lock and one of them got the lock and reset the condition, then the other threads need to check the condition after they wake up to see whether they need to wait again or can start processing.
  4. Use the same object for calling wait() and notify() method; every object has its own lock so calling wait() on object A and notify() on object B will not make any sense.


Do you need to thread this at all ? I'm wondering how big your matrices are, and whether there's any benefit in having one thread print whilst the other does the multiplication.

Perhaps it would be worth measuring this time before doing the relatively complex threading work ?

If you do need to thread it, I would create 'n' threads to perform the multiplication of the cells (perhaps 'n' is the number of cores available to you), and then use the ExecutorService and Future mechanism to dispatch multiple multiplications simultaneously.

That way you can optimise the work based on the number of cores, and you're using the higher level Java threading tools (which should make life easier). Write the results back into a receiving matrix, and then simply print this once all your Future tasks have completed.