2016-06-24 23 views
-4

在下面的代碼中爲什麼wait()之後的部分不會執行。 即使在主線程擁有鎖的對象中存在notify()也是如此。爲什麼MainClass不會從等待狀態中出來

public class MainClass { 

    public static void main(String[] args) { 
     Demo dm = new Demo(); 
     dm.add(); 

     synchronized (dm) { 
      try { 
       System.out.println("going to wait"); 
       dm.wait(); 
       System.out.println("after wait"); 
      } catch (InterruptedException e) { 
       e.printStackTrace(); 
      } 
      System.out.println(dm.result);    
     } 
    } 
} 

class Demo { 
    int result; 

    public void add(){ 
     System.out.println("in demo"); 
     synchronized (this) { 
      System.out.println("in demo syn block"); 
      for(int i=0;i<=10;i++) { 
       result=i+result;     
      } 
      System.out.println("IN demo:"+result); 
      notify();  
      } 
     } 
    } 
} 

我需要知道的是,爲什麼等待後的代碼()不執行即使通知()是there.If我嘗試解決這個使用線程然後等待(),把它弄出來的狀態自動。

+1

任何'wait'後面的'notify'都不受影響。目前尚不清楚你想在這裏做什麼。你的程序是單線程的。 –

+0

wait()和notify()不會與線程實例一起使用..如果我嘗試使用線程,那麼wait()會自動出現等待狀態 –

+0

您可以擁有多線程程序並且不使用wait和notify他們相應的'Thread'對象。 –

回答

0

您打電話的順序是錯誤的。

  1. 首先你叫Demodm.add();方法從main主題。
  2. 此方法將取對象Demo的鎖並完成任務並完成。
  3. 然後你正在主線程中鎖定dm對象並開始等待它。

發生什麼這裏是你在等待,沒有人通知。所以你的代碼將永遠不會執行寫在wait聲明