调用wait抛IllegalMonitorStateException

private void testWait(){
        Thread thread = new Thread(() -> {
            synchronized (Log.class) {
                try {
                    this.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        thread.start();
    }

当我们执行上面一段代码的时候会出现IllegalMonitorStateException  咋一看没问题啊  wait是在同步方法里啊 咋还报着异常了  但是当仔细看时发现锁对象和调用wait方法的对象不是同一对象  当出现这一情况时就会抛该异常 可以做以下更改

private void testWait(){
        Thread thread = new Thread(() -> {
            synchronized (Log.class) {
                try {
                    Log.class.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        thread.start();
    }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章