javamultithreadinginterruptlejos-nxjthread-state

IllegalThreadStateException on Thread.interrupt


I have a java program, which takes very long time to compile.

For testing purposes, I want to kill the program and restart it if compilation takes long duration.

Here is the simplified version of my code:

public class Main {

    public static void main(String[] args) {
        Thread foo = new Thread(new Foo());
        while (true) {
            foo.start();
            while (true) {
                if (needRestart()) {
                    foo.interrupt();
                    break;
                }
            }
        }
    }

}

foo.java looks a bit like this:

public class Foo implements Runnable {
    // some code
    public void run () {
        try {
            while (!Thread.currentThread().isInterrupted()) {
                // some code
            }
        } catch(InterruptedException ex) {
            Thread.currentThread().interrupt();
        }       
    }
}

The problem is that the program crashes and throws an IllegalThreadStateException

If you need the full code, here it is: full code


Solution

  • Don't start foo thread in while(true) loop. You can start a Thread only once in it's life cycle.

    Move foo.start(); above while(true)

    Refer to oracle documentation page about Thread class start() method

    public void start()
    

    Causes this thread to begin execution; the Java Virtual Machine calls the run method of this thread.

    The result is that two threads are running concurrently: the current thread (which returns from the call to the start method) and the other thread (which executes its run method).

    It is never legal to start a thread more than once. In particular, a thread may not be restarted once it has completed execution.