2013-10-04 106 views
0

我正處於非法狀態例外下面的代碼:原因拋出:IllegalMonitorStateException

synchronized (this) { 
     try { 
     Thread.currentThread().wait(); 
     notifyAll(); 
     } catch (InterruptedException e) { 
      e.printStackTrace(); 
     } 
    } 

我可以做什麼上是同步的「這樣」將捕獲監視器上的對象調用該方法,並因爲我對當前調用wait線程對象,我真的沒有鎖,我得到錯誤。請驗證我的理論。

回答

0

您打電話等待當前線程,在此調用它。

this.wait(); 

但你永遠不會得到一個notifyAll,因爲沒有線程進入synchronized塊 都不能達到notofyAll方法。他們都會先等待。

我想你想要一個線程等待另一個線程來做一些工作。

這裏是線程之間的同步如何可以工作

public class ThreadTest { 

    public static void main(String[] args) throws InterruptedException { 
     Object monitor = new Object(); 
     Thread t1 = new Thread(new R1(monitor)); 
     Thread t2 = new Thread(new R2(monitor)); 

     t1.start(); 
     t2.start(); 

     t2.join(); 
     t1.join(); 
    } 

    public static class R1 implements Runnable { 

     private Object monitor; 

     public R1(Object monitor) { 
      this.monitor = monitor; 
     } 

     public void run() { 
      System.out.println("R1 entered run"); 
      synchronized (monitor) { 
       try { 
        monitor.wait(); 
        System.out.println("R1 got monitor back"); 
       } catch (InterruptedException e) { 
        e.printStackTrace(); 
       } 
      } 
     } 

    } 

    public static class R2 implements Runnable { 

     private Object monitor; 

     public R2(Object monitor) { 
      this.monitor = monitor; 
     } 

     public void run() { 
      System.out.println("R2 entered run"); 
      synchronized (monitor) { 
       System.out.println("R2 will sleep for 1 sec"); 
       try { 
        Thread.sleep(1000); 
        System.out 
          .println("R2 will notify all threads waiting for monitor"); 
        monitor.notifyAll(); 
       } catch (InterruptedException e) { 
        e.printStackTrace(); 
       } 
      } 
     } 

    } 

} 

輸出一個短的例子是:

R1 entered run 
R2 entered run 
R2 will sleep for 1 sec 
R2 will notify all threads waiting for monitor 
R1 got monitor back 
0

您已獲得的

此(當前對象)的鎖

您在調用`

wait()的

`在當前線程這是爲什麼。

調用wait之前,你應該獲得的鎖,通知notifyAll的

0

案例1

... 
synchronized(this){ 
    this.wait(); 
} 
... 

案例2

... 
synchronized(this){ 
    Thread.currentThread.wait(); 
} 
... 

案例1是明智的代碼。它等待另一個線程調用上的「this」對象。

案例2看起來很愚蠢。它只能在當前線程和「this」是相同的對象,或者您已經在當前線程上鎖定的情況下執行。否則,你會得到IllegalMonitorStateException。在Thread對象上同步是一件壞事,因爲你不能確定還有什麼可能在它們上同步。順便說一下,如果你想要做的只是在程序中暫停一段時間,你應該sleep(),而不是wait()

0

從Java文檔的Object類的wait()方法:

拋出:IllegalMonitorStateException - 如果當前線程不是這個對象監視器的所有者 。

在代碼中,當前線程是thiswait監視器的所有者呼籲Thread.currentThread

Thread.currentThread().wait();替換爲this.wait();

相關問題