1

当我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() 。谁能告诉我是什么问题及其解决方案。-提前致谢

4

3 回答 3

2

您的wait方法需要包含在synchronized方法或lock块中,并且对象被锁定在您要等待的对象上。

在您的情况下,您应该制作方法synchronized,这相当于调用lock (this).

于 2010-10-11T12:41:41.407 回答
1

您必须首先wait获取等待变量的同步,例如

synchronized( this )
{
    this.wait( );
}

请仔细阅读 javadoc for wait并按照信函进行操作,否则您将遇到令人讨厌的惊喜。

于 2010-10-11T12:43:12.837 回答
0
  1. “wait()”所在的同步代码块
  2. 不要“通知”线程,“通知”可运行,线程是可运行的控制类,线程用监视器类包装通知/通知所有/等待
  3. 尝试使用中断并抛出“非错误”可抛出来暂停/恢复线程。
  4. 使用生产者/消费者方法
  5. 使用 fork/join 方法
  6. 使用线程池暂停和恢复线程(pause - kill runnable, resume - pool runnable)

这些方法中的任何一种都可以消除您的问题,问题本身是您尝试通知已经通知的线程,它与启动已经启动的线程一样的问题。它将抛出 IllegalMonitorStateException。

Thread 是一个可怕的 Process 解决方案,但它并不难管理。

于 2013-07-30T11:02:00.377 回答