2013-10-23 60 views
1

我在我的代碼中遇到IllegalMonitorStateException,我不知道爲什麼我收到它以及如何修復它。我當前的代碼是和錯誤是發生在try塊:如何解決IllegalMonitorStateException

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; 
    } 
} 
+0

堆棧跟蹤請。 –

回答

5

這是因爲page2.wait(1); 需要同步(鎖定)的page2對象,然後調用wait。也適合睡覺,最好使用sleep()方法。

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

上面的代碼不會拋出IllegalMonitorStateException異常。
並注意像wait(),notify()notifyAll()需要在通知之前同步對象。

這個link可能有助於解釋。

+0

現在提到睡眠()是一個小問題。也許你可以在這一點上展開? –

+0

@JohnKugelman我真的不知道會發生什麼!也許'等待(1)'是一個代碼示例,也許它真的想'wait()'超時'notify()',我只是提到問題的傢伙:) – 2013-10-23 21:23:31

+0

@JohnKugelman好的接收,感謝點,我更新了答案,我只是混合了一些東西:)感謝哥們,我擁有你一杯咖啡 – 2013-10-23 21:27:23

1

如果您試圖暫停一秒鐘,Object.wait()是錯誤的方法。您需要改爲Thread.sleep()

try { 
    Thread.sleep(1); // Pause for 1 millisecond. 
} 
catch (InterruptedException e) { 
} 
  • sleep()暫停指定的時間間隔當前線程。請注意,時間以毫秒爲單位指定,所以1表示1毫秒。要暫停1秒通過1000.

  • wait()wait()是一個同步相關的方法,用於協調不同線程之間的活動。它需要從​​塊中調用,與其他一些線程一起調用notify()notifyAll()。應該使用而不是來簡單地爲您的程序添加延遲。