How to use wait and notify in Java without IllegalMonitorStateException?

后端 未结 12 2305
后悔当初
后悔当初 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:10

    You have properly guarded your code block when you call wait() method by using synchronized(this).

    But you have not taken same precaution when you call notify() method without using guarded block : synchronized(this) or synchronized(someObject)

    If you refer to oracle documentation page on Object class, which contains wait() ,notify(), notifyAll() methods, you can see below precaution in all these three methods

    This method should only be called by a thread that is the owner of this object's monitor

    Many things have been changed in last 7 years and let's have look into other alternatives to synchronized in below SE questions:

    Why use a ReentrantLock if one can use synchronized(this)?

    Synchronization vs Lock

    Avoid synchronized(this) in Java?

提交回复
热议问题