如何在Java中杀死Java .lang. thread ?


当前回答

通常不杀死、停止或中断线程(或检查它是否被中断()),而是让它自然终止。

这很简单。你可以在run()方法中使用任何循环和(volatile)布尔变量来控制线程的活动。您还可以从活动线程返回到主线程以停止它。

这样你就优雅地杀死了一个线程:)。

其他回答

There is of course the case where you are running some kind of not-completely-trusted code. (I personally have this by allowing uploaded scripts to execute in my Java environment. Yes, there are security alarm bell ringing everywhere, but it's part of the application.) In this unfortunate instance you first of all are merely being hopeful by asking script writers to respect some kind of boolean run/don't-run signal. Your only decent fail safe is to call the stop method on the thread if, say, it runs longer than some timeout.

但是,这只是“体面的”,而不是绝对的,因为代码可以捕获ThreadDeath错误(或您显式抛出的任何异常),而不是像一个绅士线程应该做的那样重新抛出它。所以,AFAIA的底线是没有绝对的故障保险。

一种方法是设置一个类变量并将其用作哨兵。

Class Outer {
    public static volatile flag = true;

    Outer() {
        new Test().start();
    }
    class Test extends Thread {

        public void run() {
            while (Outer.flag) {
                //do stuff here
            }
        }
    }

}

设置一个外部类变量,如上面例子中的flag = true。将其设置为false以“杀死”线程。

我想根据所积累的意见补充几点看法。

Thread.stop() will stop a thread if the security manager allows it. Thread.stop() is dangerous. Having said that, if you are working in a JEE environment and you have no control over the code being called, it may be necessary; see Why is Thread.stop deprecated? You should never stop stop a container worker thread. If you want to run code that tends to hang, (carefully) start a new daemon thread and monitor it, killing if necessary. stop() creates a new ThreadDeathError error on the calling thread and then throws that error on the target thread. Therefore, the stack trace is generally worthless. In JRE 6, stop() checks with the security manager and then calls stop1() that calls stop0(). stop0() is native code. As of Java 13 Thread.stop() has not been removed (yet), but Thread.stop(Throwable) was removed in Java 11. (mailing list, JDK-8204243)

这里有一些关于这个主题的好读物:

如何处理InterruptedException?

干净地关闭线程

我没有得到中断工作在Android,所以我用这个方法,工作完美:

boolean shouldCheckUpdates = true;

private void startupCheckForUpdatesEveryFewSeconds() {
    Thread t = new Thread(new CheckUpdates());
    t.start();
}

private class CheckUpdates implements Runnable{
    public void run() {
        while (shouldCheckUpdates){
            //Thread sleep 3 seconds
            System.out.println("Do your thing here");
        }
    }
}

 public void stop(){
        shouldCheckUpdates = false;
 }