2013-10-10 34 views
-1
public class ThreadConfusion 
{ 
    public static void main(String[] args) 
    { 
     System.out.print("1 "); 
     synchronized (args) 
     { 
      System.out.println(" 2"); 
      try 
      { 
       args.wait(); 
      } 
      catch (InterruptedException e) 
      { 
       System.out.println("exception"); 
      } 
     } 
     System.out.println("3 "); 
    } //end of the main method 
} // end of the class 

O/P混亂有關使用Java同步對象的塊

1 2 

爲何O/P爲1 2,而不是1 2 3發生了什麼事究竟 那邊我無能能任何1請向我解釋.. 謝謝你

+1

你爲什麼叫wait()的?它等着你打電話通知() –

+0

更重要的是:你期望調用'args.notify()'誰?這裏沒有其他線程... – ppeterka

回答

0

因爲沒有人調用notify()。您的主線程將無限期地等待。

wait()的Javadoc:

造成當前線程等待,直到其他線程調用 notify()方法或此對象的notifyAll的()方法。

如果你想等電話Thread.sleep();

0
args.wait(); 

wait()

造成當前線程等待,直到其他線程調用notify()方法或此對象的notifyAll的()方法。

你是在告訴wait(在對象上的鎖)的threadmain)永遠。

try{args.wait(5000);} 

看到那個5秒後,等待完成,並打印3

或致電notify()