呼叫wait()内线程的run()方法

问题描述:

我很好奇为什么这不起作用?我收到IllegalMonitorStateException。这是Runnable的运行方法,该方法已被封装在线程中并启动。呼叫wait()内线程的run()方法

public void run() 
{ 
    while(true) 
    { 
     System.out.println("Hello World"); 

     synchronized(Thread.currentThread()) 
     { 
      try{ 
       wait();  
      } 
      catch (InterruptedException e){} 
     } 
    } 
} 
+3

的[抛出:IllegalMonitorStateException API(http://docs.oracle.com/javase/7/docs/api/java/lang/IllegalMonitorStateException.html)和[对象API](http://docs.oracle.com/javase/7/docs/api/java/lang/Object.html#wait())都有关于此的有用信息。你读过这些吗?如果没有,请这样做。如果是这样,那么在那里显示的信息会让你感到困惑? – 2012-02-07 01:52:49

+2

另外,请查看关于Java线程和监视器的优秀文章:[线程同步的内部Java虚拟机 的第20章](http://www.artima.com/insidejvm/ed2/threadsynch.html) – 2012-02-07 01:58:16

+0

我意识到它恰好在检查并修复它之前。我的错。感谢您的资源,我一定会看看他们! – user34531 2012-02-07 02:01:18

按照Javadoc文档wait()

IllegalMonitorStateException - if the current thread is not the owner of the object's monitor. 

当你调用wait(),要调用它的可运行实例。由于您的同步块位于当前线程上,而不是this,因此您不保留当前实例的锁定。您应该将您的代码更改为synchronized(this)以避免发生异常。

您在拥有另一个对象的监视器(Thread.currentThread()的结果)的同时在一个对象(Runnable)上调用wait()。您必须拥有显示器(synchronize相同的对象,您可以拨打wait()。所以这不会导致错误:

public void run() { 
    synchronized(this) { 
     try { 
      wait(); 
     } catch (InterruptedException e) { } 
    } 
}