【问题标题】:How to fix IllegalMonitorStateException如何修复 IllegalMonitorStateException
【发布时间】:2013-10-23 20:58:07
【问题描述】:

我在我的代码中遇到了 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;
  }
}

【问题讨论】:

    标签: java error-handling wait


    【解决方案1】:

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

    synchronized(page2){//page2 should not be null
        page2.wait();//waiting for notify
    }
    

    以上代码不会抛出IllegalMonitorStateException 异常。
    并注意像wait()notify()notifyAll()需要在通知之前同步对象。

    这个link 可能有助于解释。

    【讨论】:

    • 现在提到sleep() 是一件小事。也许你可以在这一点上展开?
    • @JohnKugelman 我真的不知道会发生什么!也许wait(1) 是一个代码示例,也许它真的想wait()notify() 超时,我只是提到问题老兄:)
    • @JohnKugelman 很好,谢谢你的观点,我更新了答案,我只是混淆了一些东西 :) 谢谢哥们,我给你一杯咖啡
    【解决方案2】:

    如果您只想暂停一秒钟,Object.wait() 是错误的方法。你想要Thread.sleep()

    try {
        Thread.sleep(1);  // Pause for 1 millisecond.
    }
    catch (InterruptedException e) {
    }
    
    • sleep() 将当前线程暂停指定的时间间隔。请注意,时间以毫秒为单位指定,因此 1 表示 1 毫秒。暂停 1 秒通过 1000。

    • wait() 是一种与同步相关的方法,用于协调不同线程之间的活动。它需要从synchronized 块内部调用,同时其他线程调用notify()notifyAll()。它应该用于简单地为您的程序添加延迟。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-11
      • 2011-08-17
      • 2013-08-15
      • 1970-01-01
      相关资源
      最近更新 更多