当我在下面的代码中使用wait()方法时,它抛出了以下异常
Exception in thread "AWT-EventQueue-0" java.lang.IllegalMonitorStateException代码如下:
private void newMenuItemActionPerformed(java.awt.event.ActionEvent evt) {
newFileChooser = new JFileChooser();
int returnVal = newFileChooser.showSaveDialog(null);
if (returnVal == JFileChooser.APPROVE_OPTION) {
filename = newFileChooser.getSelectedFile();
JFrame mainFrame = NetSimApp.getApplication().getMainFrame();
networktype = new NetType(mainFrame);
networktype.setLocationRelativeTo(mainFrame);
NetSimApp.getApplication().show(networktype);
try {
this.wait();
} catch (InterruptedException ex) {
Logger.getLogger(NetSimView.class.getName()).log(Level.SEVERE, null, ex);
}
if (!NetType.validip) {
statusTextArea.append("File not created:Select Network Type.\n");
}
newNodeMenuItem.setEnabled(true);
} else {
newNodeMenuItem.setEnabled(false);
statusTextArea.append("File not created:Access cancelled by user.\n");
}
}实际上,我正在调用一个jDialog类的对象,我希望对话框对象应该首先完成,然后它应该通知上面的给定代码。我已经在该类中指定了notify()。谁能告诉我问题出在哪里,解决办法是什么?提前使用-Thanks
发布于 2010-10-11 20:41:41
您的wait方法需要包含在synchronized方法或lock块中,并且对象被锁定在您想要等待的对象上。
在本例中,您应该将该方法设置为synchronized,这等效于调用lock (this)。
发布于 2010-10-11 20:43:13
您必须通过获取wait变量的同步来启动wait,例如
synchronized( this )
{
this.wait( );
}请仔细阅读wait的javadoc,并严格遵循它,否则您将遇到令人不快的惊喜。
发布于 2013-07-30 19:02:00
()”是
这些方法中的任何一种都可以消除你的问题,问题本身就是你试图通知已经被通知的线程,它的问题和启动已经启动的线程一样。它将抛出一个IllegalMonitorStateException。
线程是一个写得很糟糕的进程解决方案,但它并不难管理。
https://stackoverflow.com/questions/3906228
复制相似问题