mrCyborg mrCyborg - 1 year ago 82
Java Question

IllegalThreadStateException on Thread.interrupt

I have a java program that takes a very long time to compile, for testing purposes I wanted to be able to kill the program and restart it at any time without the long waiting.

Here is a simplefied version of my code:

public class Main {

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

} 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) {

The problem is that the program crashes and throws an IllegalThreadStateException

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

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download