synchronized object not locked by thread before notifyAll()

前端 未结 1 1540
感动是毒
感动是毒 2020-12-20 22:44

I want to have a boolean to notify some sections of the system that a specific service started.

For some strange reason I\'m getting the error java.lang.Illega

相关标签:
1条回答
  • 2020-12-20 22:46

    The line

    MyService.notifier = Boolean.valueOf(true);
    

    swaps out the object you're locking on, it overwrites the variable with a reference to a new object. So the object you acquired the lock on upon entering the block is not the same one that you're calling notifyAll on. All notifyAll knows is it hasn't acquired the lock on the object it's being called on, which is the new object created after the synchronize block was entered.

    All the threads need to be using the same lock. Like Ian Roberts said, the lock belongs to the object. If you overwrite the object you have a new lock.

    0 讨论(0)
提交回复
热议问题