java - Thread.interrupt 上的 IllegalThreadStateException

标签 java multithreading interrupt lejos-nxj thread-state

我有一个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/

相关文章:

java - 正则表达式匹配整个单词或运算符

java - 如何在 Eclipse 4 RCP 中获取 IHandlerService 对象?

java - 如何在Spring RestTemplate中实现批处理

java - java原始整数是设计的还是偶然的?

java - 后台 Android Activity - 记录 GPS

c# - 连续发出多个 Web 请求的最简单方法是什么?

python - 如何在Python中让线程等待?

linux - 为什么我们需要在 ARM Linux cpu_idle 中禁用 WFI 之前的中断

linux - "kernel preemption"和 "interrupt"之间有什么区别吗?

operating-system - 直接连接到 CPU 的 PCIe 插槽的中断路由