Search code examples
javamultithreadingconsolewaitnotify

Java Simple and Single Threading IllegalMonitorStateException


I have a problem in Java about Threading, its with a Single Thread and its about stopping a Thread and continue.

What my Code does: Class MainWindow Creates a Threadreference and in a endloop it starts and stops it.

The Class MyThread starts the Thread. The run method is pretty short and all it does is do: 1. move the mouse to the left side of the screen then 2. move the mouse to the right side of the screen

When i start the program i get instantly a IllegalMonitorStateException and don't know how to fix it.

public class MainWindow
{
    public static void main(String[] args) throws Exception 
    {
        MyThread mt = new MyThread();
        while(true)
        {
            mt.start();
            Thread.sleep(1000);
            mt.wait();
        }
    }
}

public class MyThread implements Runnable 
{
    private Thread th;
    public MyThread() throws Exception
    {
        th = new Thread();
        th.start();
    }
    public void start() throws InterruptedException
    {
        synchronized(this){
        th.wait();
        }
    }
    public void wait()
    {
        synchronized(this){
        th.notifyAll();
        }
    }
    @Override
    public void run() 
    {
       //do something
    }
}

Thanks for any help! :)


Solution

  • while(true)
            {
                mt.start();
                Thread.sleep(1000);
                mt.wait();
            }
    

    You should not make the running thread runnable. ie) you cannot start the thread which is already running.