Thread.interrupt 上的 IllegalThreadStateException

IllegalThreadStateException on Thread.interrupt

我有一个java程序,编译需要很长时间。

出于测试目的,如果编译时间较长,我想终止程序并重新启动它。

这是我的代码的简化版本:

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 看起来有点像这样:

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

问题是程序崩溃并抛出 IllegalThreadStateException

如果你需要完整的代码,这里是:full code

不要在 while(true) 循环中启动 foo 线程。 Thread 在其生命周期中只能启动一次。

foo.start();移到while(true)

上方

参考有关 Thread class start() 方法的 oracle 文档页面

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.

IllegalThreadStateException 当您尝试更改线程的状态或当您尝试在同一线程处于 运行 状态时再次调用 start 方法时发生。 但是在你的情况下,如果你想中断你的线程,让它进入 sleep() 并且当你希望你在该线程自动退出睡眠之前中断调用 notify()