IllegalMonitorStateException while calling wait() in run()

后端 未结 1 513
无人共我
无人共我 2020-12-22 12:46

I have created an java thread and passed an stack reference to it\'s constructor, which initialize thread stack reference. In run method i have created an synchronized block

1条回答
  •  礼貌的吻别
    2020-12-22 13:41

    For wait() (or notify()) to work, you must call it on the same object. What you have now is the same as

     synchronized (stack) {
        if(stack.isEmpty()){
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
     }  
    

    instead you should do

     synchronized (stack) {
        if(stack.isEmpty()){
            try {
                stack.wait(); // wait on the same object synchronized.
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
     }  
    

    Note: as wait can wake spuriously you have do this in a loop or your method could return prematurely.

     synchronized (stack) {
        while (stack.isEmpty()){
            try {
                stack.wait(); 
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
     }  
    

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