当我在下面的代码中使用 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() 。谁能告诉我问题是什么及其解决方案。 -提前致谢
最佳答案
您的wait
方法需要包含在synchronized
方法或lock
block 中,对象被锁定在您想要的对象上等待。
在您的情况下,您应该使方法同步
,这等同于调用lock (this)
。
关于java - 等待并通知问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3906228/