Why must wait() always be in synchronized block

后端 未结 10 1331
傲寒
傲寒 2020-11-22 06:18

We all know that in order to invoke Object.wait(), this call must be placed in synchronized block, otherwise an IllegalMonitorStateException is thrown. But what\'s t

10条回答
  •  闹比i
    闹比i (楼主)
    2020-11-22 06:48

    Thread wait on the monitoring object (object used by synchronization block), There can be n number of monitoring object in whole journey of a single thread. If Thread wait outside the synchronization block then there is no monitoring object and also other thread notify to access for the monitoring object, so how would the thread outside the synchronization block would know that it has been notified. This is also one of the reason that wait(), notify() and notifyAll() are in object class rather than thread class.

    Basically the monitoring object is common resource here for all the threads, and monitoring objects can only be available in synchronization block.

    class A {
       int a = 0;
      //something......
      public void add() {
       synchronization(this) {
          //this is your monitoring object and thread has to wait to gain lock on **this**
           }
      }
    

提交回复
热议问题