在run()中调用wait()时出现IllegalMonitorStateException

我创建了一个java线程并将堆栈引用传递给它的构造函数,该构造函数初始化线程堆栈引用。 在run方法中,我已经创建了一个带有该堆栈对象的synchronized块,当我在synchronized块中运行时调用wait,我得到了IllegalMonitorStateException。

线程类:

public class Producer extends Thread { Stack stack=null; public Producer(Stack stack) { this.stack=stack; } @Override public void run() { synchronized (stack) { if(stack.isEmpty()){ try { wait(); } catch (InterruptedException e) { e.printStackTrace(); } } } } } 

主类:

 public class MainClass { public static void main(String[] args) { Stack stack=new Stack(); Producer p=new Producer(stack); p.start(); } } 

输出:

 Exception in thread "Thread-0" java.lang.IllegalMonitorStateException at java.lang.Object.wait(Native Method) at java.lang.Object.wait(Object.java:485) at demo.Producer.run(Producer.java:20) 

要使wait()(或notify())起作用,必须在同一对象上调用它。 你现在拥有的是和

  synchronized (stack) { if(stack.isEmpty()){ try { this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } } 

相反,你应该这样做

  synchronized (stack) { if(stack.isEmpty()){ try { stack.wait(); // wait on the same object synchronized. } catch (InterruptedException e) { e.printStackTrace(); } } } 

注意:因为等待可以虚假地唤醒你在循环中执行此操作或者您的方法可能过早地返回。

  synchronized (stack) { while (stack.isEmpty()){ try { stack.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } }