2013-01-17 38 views
0

wait()和notify()不是靜態的,所以編譯器應該給出錯誤,必須從靜態上下文中調用wait。wait和notify不是靜態的

public class Rolls { 
    public static void main(String args[]) { 
    synchronized(args) { 
     try { 
      wait(); 
     } catch(InterruptedException e) 
     { System.out.println(e); } 
    } 
    } 
} 

但是,以下代碼編譯並正常運行。爲什麼編譯器不在這裏給出錯誤?或者,爲什麼編譯器在前面的代碼中給出了必須從靜態上下文中調用等待的錯誤?

public class World implements Runnable { 
    public synchronized void run() { 
    if(Thread.currentThread().getName().equals("F")) { 
     try { 
      System.out.println("waiting"); 
      wait(); 
      System.out.println("done"); 
     } catch(InterruptedException e) 
     { System.out.println(e); } 
    } 
    else { 
     System.out.println("other"); 
     notify(); 
     System.out.println("notified"); 
    } 
    } 
    public static void main(String []args){ 
    System.out.println("Hello World"); 
    World w = new World(); 
    Thread t1 = new Thread(w, "F"); 
    Thread t2 = new Thread(w); 
    t1.start(); 
    t2.start(); 
    } 
} 
+0

不知道你的困惑在哪裏,但是在靜態方法中創建'new World()'不會使'new'ed實例靜態,實例就是一個實例。同時向你的'World'類添加一個靜態方法並不會使該類的其他方法以某種方式靜態。 – hyde

回答

5

要調用的等待和從一個實例方法(public synchronized void run()),其定義也不是一成不變的通知。

  • 如果您在main方法中調用wait方法(靜態方法),則會得到您期望的錯誤。
  • 或者,您可以將方法簽名更改爲public static synchronized void run(),但是您也會收到另一個編譯錯誤,因爲您沒有再執行Runnable。
+0

對不起,我的錯誤。 – amrita

+1

只是爲了添加...這些方法是Object類的方法,並在直接調用時鎖定/解鎖當前對象。你可以想到this.wait()等等。第二種情況世界的對象將被鎖定/解鎖。 – Amit

0

什麼時候編譯器給等候必須從靜態CONTEX

該錯誤消息是,該方法不能從靜態上下文被稱爲被稱爲錯誤。如果您嘗試在沒有實例的情況下在static方法中使用它,則會出現此錯誤。

相關問題