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


当前回答

我没有得到中断工作在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;
 }

其他回答

你有办法做到这一点。但如果你不得不使用它,要么你是一个糟糕的程序员,要么你使用的是一个糟糕的程序员编写的代码。所以,你应该考虑停止成为一个糟糕的程序员或停止使用这些糟糕的代码。 这种解决方案只适用于别无选择的情况。

Thread f = <A thread to be stopped>
Method m = Thread.class.getDeclaredMethod( "stop0" , new Class[]{Object.class} );
m.setAccessible( true );
m.invoke( f , new ThreadDeath() );

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

如何处理InterruptedException?

干净地关闭线程

一般来说你不会…

你可以使用Thread.interrupt() (javadoc link)命令它中断正在做的事情。

在javadoc中有一个很好的解释(java technote链接)

在用Java开发了15年之后,有一件事我想对世界说。

弃用Thread.stop()和所有反对其使用的神圣之战只是另一个坏习惯或设计缺陷不幸成为现实…(如。想谈谈Serializable接口吗?)

争论的焦点在于,杀死线程会使对象处于不一致的状态。所以呢?欢迎来到多线程编程。你是一个程序员,你需要知道你在做什么,是的。杀死线程会使对象处于不一致状态。如果你担心它使用一个标志,让线程优雅地退出;但有很多时候,我们没有理由担心。

但没有. .如果你输入thread.stop(),你很可能会被所有查看/注释/使用你代码的人杀死。所以你必须使用一个标志,调用interrupt(),在你的代码周围放置if(!标志),因为你根本没有循环,最后祈祷你用来进行外部调用的第三方库是正确编写的,并且没有不正确地处理InterruptException。

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

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)