calling Object.notify() before Object.wait()

后端 未结 4 1689
独厮守ぢ
独厮守ぢ 2021-01-06 03:46

If there is no thread which is waiting, using Object.wait() , any calls to Object.notify() or Object.notifyAll() have no effect. I hav

4条回答
  •  盖世英雄少女心
    2021-01-06 04:33

    Use a flag to indicating a notification. Read the flag before entering wait and act accordingly.

    boolean stopped = false;
    
    public void run(){
       synchronized(object){
          while(!stopped)
            object.wait();
       }
    
    }
    
    public void stop(){
      synchronized(object){
        stopped=true;
        object.notify();
      }
    
    }
    

提交回复
热议问题