如何在Java中杀死Java .lang. thread ?
当前回答
我想根据所积累的意见补充几点看法。
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?
干净地关闭线程
你有办法做到这一点。但如果你不得不使用它,要么你是一个糟糕的程序员,要么你使用的是一个糟糕的程序员编写的代码。所以,你应该考虑停止成为一个糟糕的程序员或停止使用这些糟糕的代码。 这种解决方案只适用于别无选择的情况。
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() );
请参阅Sun的这篇文章,了解他们为什么弃用thread .stop()。它将详细说明为什么这是一个糟糕的方法,以及应该做些什么来安全地停止线程。
他们推荐的方法是使用一个共享变量作为标志,要求后台线程停止。这个变量可以由请求线程终止的另一个对象设置。
在用Java开发了15年之后,有一件事我想对世界说。
弃用Thread.stop()和所有反对其使用的神圣之战只是另一个坏习惯或设计缺陷不幸成为现实…(如。想谈谈Serializable接口吗?)
争论的焦点在于,杀死线程会使对象处于不一致的状态。所以呢?欢迎来到多线程编程。你是一个程序员,你需要知道你在做什么,是的。杀死线程会使对象处于不一致状态。如果你担心它使用一个标志,让线程优雅地退出;但有很多时候,我们没有理由担心。
但没有. .如果你输入thread.stop(),你很可能会被所有查看/注释/使用你代码的人杀死。所以你必须使用一个标志,调用interrupt(),在你的代码周围放置if(!标志),因为你根本没有循环,最后祈祷你用来进行外部调用的第三方库是正确编写的,并且没有不正确地处理InterruptException。
试图突然终止线程是众所周知的糟糕编程实践,也是糟糕应用程序设计的证据。多线程应用程序中的所有线程显式或隐式地共享相同的进程状态,并被迫相互协作以保持一致,否则您的应用程序将容易出现很难诊断的错误。因此,开发人员有责任通过仔细和清晰的应用程序设计来保证这种一致性。
对于受控线程终止,有两种主要的正确解决方案:
使用共享volatile标志 使用Thread.interrupt()和Thread.interrupted()方法。
关于突发线程终止相关问题的详细解释,以及受控线程终止的错误和正确解决方案的示例,可以在这里找到:
https://www.securecoding.cert.org/confluence/display/java/THI05-J.+Do+not+use+Thread.stop%28%29+to+terminate+threads
推荐文章
- 从枚举中选择一个随机值?
- 如何从URL获取参数与JSP
- 如何在Eclipse中生成Javadoc注释?
- 找到java类从哪里加载
- 从集合中随机选取一个元素
- 为什么x == (x = y)和(x = y) == x不一样?
- 什么Java 8流。收集等价物可在标准Kotlin库?
- 等待未来的名单
- 如何检查JSON键是否存在?
- 为什么MongoDB Java驱动在条件中使用随机数生成器?
- 即使从未抛出异常,使用try-catch块的代价是否昂贵?
- 什么时候我们应该使用观察者和可观察对象?
- Java中的split()方法对点(.)不起作用。
- Eclipse调试器总是阻塞在ThreadPoolExecutor上,没有任何明显的异常,为什么?
- Java生成两个给定值之间的随机数