如何修复IllegalMonitorStateException

Cte*_*h45 2 java error-handling wait

我在我的代码中遇到IllegalMonitorStateException,我不知道为什么我收到它以及如何解决它.我当前的代码是,并且try块中发生错误:

  public static String scrapeWebsite() throws IOException {

    final WebClient webClient = new WebClient();
    final HtmlPage page = webClient.getPage(s);
    final HtmlForm form = page.getForms().get(0);
    final HtmlSubmitInput button = form.getInputByValue(">");
    final HtmlPage page2 = button.click();
    try {
    page2.wait(1);
    }
    catch(InterruptedException e)
    {
      System.out.println("error");
    }
    String originalHtml = page2.refresh().getWebResponse().getContentAsString();
    return originalHtml;
  }
}
Run Code Online (Sandbox Code Playgroud)

小智 6

这是因为page2.wait(1); 你需要同步(锁定)page2对象然后调用wait.也适合睡觉,最好使用sleep()方法.

synchronized(page2){//page2 should not be null
    page2.wait();//waiting for notify
}
Run Code Online (Sandbox Code Playgroud)

上面的代码不会抛出IllegalMonitorStateException异常.
并注意到wait(),notify()并且notifyAll()需要在通知之前同步对象.

这个链接可能有助于解释.