简体   繁体   English

Thread.interrupt上的IllegalThreadStateException

[英]IllegalThreadStateException on Thread.interrupt

I have a java program, which takes very long time to compile. 我有一个Java程序,需要很长时间才能编译。

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: 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();
        }       
    }
}

The problem is that the program crashes and throws an IllegalThreadStateException 问题是程序崩溃并抛出IllegalThreadStateException

If you need the full code, here it is: full code 如果您需要完整的代码,则为: 完整的代码

Don't start foo thread in while(true) loop. 不要在while(true)循环中启动foo线程。 You can start a Thread only once in it's life cycle. 您只能在一个生命周期中启动一个Thread

Move foo.start(); 移动foo.start(); above while(true) 以上while(true)

Refer to oracle documentation page about Thread class start() method 有关线程start()方法的信息,请参考oracle文档页面

public void start()

Causes this thread to begin execution; 使该线程开始执行; the Java Virtual Machine calls the run method of this thread. Java虚拟机将调用此线程的run方法。

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). 结果是两个线程同时运行:当前线程(从调用返回到start方法)和另一个线程(执行其run方法)。

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 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. IllegalThreadStateException当您试图改变你的线程的状态或当您尝试再次调用同一个线程start方法,一旦它处于运行状态发生。 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. 但是在您的情况下,如果您想中断线程,请使其进入sleep() ,并希望在该线程自动退出睡眠之前中断对该线程的调用notify()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM