Why must wait() always be in synchronized block

后端 未结 10 1119
傲寒
傲寒 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条回答
  •  终归单人心
    2020-11-22 07:12

    The problem it may cause if you do not synchronize before wait() is as follows:

    1. If the 1st thread goes into makeChangeOnX() and checks the while condition, and it is true (x.metCondition() returns false, means x.condition is false) so it will get inside it. Then just before the wait() method, another thread goes to setConditionToTrue() and sets the x.condition to true and notifyAll().
    2. Then only after that, the 1st thread will enter his wait() method (not affected by the notifyAll() that happened few moments before). In this case, the 1st thread will stay waiting for another thread to perform setConditionToTrue(), but that might not happen again.

    But if you put synchronized before the methods that change the object state, this will not happen.

    class A {
    
        private Object X;
    
        makeChangeOnX(){
            while (! x.getCondition()){
                wait();
                }
            // Do the change
        }
    
        setConditionToTrue(){
            x.condition = true; 
            notifyAll();
    
        }
        setConditionToFalse(){
            x.condition = false;
            notifyAll();
        }
        bool getCondition(){
            return x.condition;
        }
    }
    

提交回复
热议问题