调用wait()时发生java.lang.IllegalMonitorStateException;在java中

时间:2014-07-08 17:55:41

标签: java

我已经为一个简单的计数器编写了这个java代码,有两个JButtons用于运行计数器,另一个用于停止计数器,当我运行我的代码并单击等待按钮(java.lang.IllegalMonitorStateException)异常发生在( Main.java:42)。请告诉我代码中的问题是什么?

import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;


public class Main extends JFrame implements ActionListener, Runnable {


    JLabel time = new JLabel();
    JButton wait = new JButton("wait");
    JButton notify = new JButton("notify");
    Thread count = new Thread(this);
    int sec=0;

    public static void main(String arg[]) {
        new Main();
    }

    public Main() {
        super("Counter");
        setSize(250,100);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setLayout(new FlowLayout());
        setVisible(true);
        add(time);
        add(wait);
        add(notify);
        notify.setEnabled(false);
        wait.addActionListener(this);
        notify.addActionListener(this);
        count.start();
    }

    public void actionPerformed(ActionEvent e) {
        if(e.getSource()==wait) {
            try
            {
                count.wait();
                wait.setEnabled(false);
                notify.setEnabled(true);
            }
            catch (Exception e1) {
                e1.printStackTrace();
            }
        }
        else if(e.getSource()==notify) {
            count.notify();
            wait.setEnabled(true);
            notify.setEnabled(false);
        }
    }


    public void run() {
        synchronized (this) {
            while(true) {
                time.setText(String.format("seconds=%d",sec));
                try
                {
                    Thread.sleep(1000);
                }
                catch (InterruptedException e) {
                    e.printStackTrace();
                }
                sec++;
            }
        }
    }   
}

1 个答案:

答案 0 :(得分:1)

您应该只在 synchronized 上下文中调用wait()notify()。否则你将IllegalMonitorSateException