2013-10-10 31 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()