How to use wait and notify in Java without IllegalMonitorStateException?

后端 未结 12 2123
后悔当初
后悔当初 2020-11-22 02:21

I have 2 matrices and I need to multiply them and then print the results of each cell. As soon as one cell is ready I need to print it, but for example I need to print the [

12条回答
  •  悲&欢浪女
    2020-11-22 03:12

    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.

提交回复
热议问题