1

I have written this java code for a simple counter, there are two JButtons one for running counter and other one for stopping the counter, when I run my code and click wait button (java.lang.IllegalMonitorStateException) exception occurs at (Main.java:42). Please tell what is the problem in my code?

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++;
            }
        }
    }   
}
user3808922
  • 61
  • 1
  • 1
  • 3

1 Answers1

1

You should call wait() and notify() only in synchronized contexts. Else you will have IllegalMonitorSateException.

TheLostMind
  • 35,966
  • 12
  • 68
  • 104