0

我试图在“slp”对象上调用 wait() 函数,然后在 1000 次磨机后将其唤醒,但在调用 notify() 后,我收到“IllegalMonitorStateException”错误而不是消息“Finished ...”

class Class1 extends Thread{

 boolean newTxt = false;
private Sleep slp = null;

synchronized public void put(Sleep slp)
{
  thus.slp = slp;
 try{ slp.wait();}catch(Exception x){} 

}
synchronized public void wakeup()
{
  slp.notify();
}
public void run()
{
  while(slp == null ); 
  try{ sleep(1000);}catch(Exception x){} 
  wakeup();

 }
}

class Sleep extends Thread {

Class1 t;
Sleep(Class1 t) {
this.t=t;
}
 public void run() {
 System.out.println("Started");
t.put(this);
System.out.println("Finished after 1000 mills");
 }

}

public class Koord {

  public static void main(String[] args) {
   Class1 t = new Class1();
 Sleep t1 = new Sleep(t);
 t1.start();
 t.start();
 }
}
4

1 回答 1

3

您需要成为“对象监视器的所有者”才能调用它。您的notify方法都同步在其他对象上this,而您notify()在其他对象上。只需调用wait()notify()

IllegalMonitorStateException抛出以指示线程已尝试在对象的监视器上等待,或通知其他线程在对象的监视器上等待但不拥有指定的监视器。

于 2013-05-06T16:45:31.910 回答