gpt4 book ai didi

java - Thread.interrupt 上的 IllegalThreadStateException

转载 作者:行者123 更新时间:2023-12-01 18:11:21 24 4
gpt4 key购买 nike

我有一个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) 上方

引用oracle文档页面关于Threadstart()方法

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.

关于java - Thread.interrupt 上的 IllegalThreadStateException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32782867/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com