0

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

Ravindra babu
  • 37,698
  • 11
  • 250
  • 211
nloomans
  • 220
  • 2
  • 11
  • it takes long to compile or to run? – ACV Sep 25 '15 at 13:07
  • @ACV it takes long to compile, I'm running this on an EV3 – nloomans Sep 25 '15 at 13:10
  • Any time you have an exception, you should include its entire stack trace in your question. – VGR Sep 25 '15 at 13:13
  • I think this happens here `} catch(InterruptedException ex) { Thread.currentThread().interrupt(); } ` because you're trying to interrup an interrupted thread. do a `ex.printStackTrace();` – ACV Sep 25 '15 at 13:24

2 Answers2

4

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.

Ravindra babu
  • 37,698
  • 11
  • 250
  • 211
0

IllegalThreadStateException occurs when you try to change the state of your thread or when you try to again calling the start method on same thread once it is in running state. But in your case if you want to interrupt your thread make it to go to sleep() in and when you want you to interrupt call notify() on that thread before it comes out of sleep automatically.

egor.zhdan
  • 4,555
  • 6
  • 39
  • 53
siddhartha jain
  • 1,006
  • 10
  • 16