Java:notify() 上的 IllegalMonitorStateException

标签 java multithreading notify

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

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();
 }
}

最佳答案

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

IllegalMonitorStateException ,抛出该异常表示线程已尝试在对象的监视器上等待,或通知在不拥有指定监视器的情况下在对象的监视器上等待的其他线程。

关于Java:notify() 上的 IllegalMonitorStateException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16403189/

相关文章:

java - 在ZK中我们可以PostNotifyChange多个变量吗

java - 简化几个 boolean 条件java

java - 使用 Java 或 iText 生成两个完全相同的 PDF

java - JVisualVM 内存采样 : Remote applications are not supported

swift - 断言在应该传递 : why? 的地方失败

Java:在多个线程上等待/通知

java - 我必须将文件放在哪里才能使用文件附加器 log4j2

c++ - 一种读取/写入大型场景文件的有效方法

java - 在Java中,您必须有一个具有线程将访问的共享变量的类吗?

Java线程wait()notify()在一个方法中