java 在java中杀死一个正在运行的线程?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3130701/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 00:29:53  来源:igfitidea点击:

killing a running thread in java?

javamultithreading

提问by JavaUser

How to kill a running thread in java

如何在java中杀死正在运行的线程

回答by Bozho

You can ask the thread to interrupt, by calling Thread.interrupt()

您可以通过调用来要求线程中断 Thread.interrupt()

Note that a few other methods with similar semantics exist - stop()and destroy()- but they are deprecated, because they are unsafe. Don't be tempted to use them.

请注意,存在一些具有类似语义的其他方法 -stop()并且destroy()- 但它们已被弃用,因为它们不安全。不要试图使用它们。

回答by Eyal Schneider

As Bozho said, Thread.interrupt() is the generic and right way to do it. But remember that it requires the thread to cooperate; It is very easy to implement a thread that ignores interruption requests.

正如 Bozho 所说,Thread.interrupt() 是通用且正确的方法。但要记住,它需要线程配合;实现一个忽略中断请求的线程是很容易的。

In order for a piece of code to be interruptible this way, it shouldn't ignore any InterruptedException, and it should check the interruption flag on each loop iteration (using Thread.currentThread().isInterrupted()). Also, it shouldn't have any non-interruptible blocking operations. If such operations exist (e.g. waiting on a socket), then you'll need a more specific interruption implementation (e.g. closing the socket).

为了让一段代码以这种方式可中断,它不应该忽略任何 InterruptedException,并且应该在每次循环迭代中检查中断标志(使用 Thread.currentThread().isInterrupted())。此外,它不应该有任何不可中断的阻塞操作。如果存在此类操作(例如等待套接字),那么您将需要更具体的中断实现(例如关闭套接字)。

回答by Incognito

Shortly you need Thread.interrupt()

不久你需要 Thread.interrupt()

For more details check the section How do I stop a thread that waits for long periods (e.g., for input)in this article Why Are Thread.stop, Thread.suspend,Thread.resumeand Runtime.runFinalizersOnExitDeprecated?.

有关详情,请部分How do I stop a thread that waits for long periods (e.g., for input)在这篇文章中,为什么Thread.stopThread.suspendThread.resumeRuntime.runFinalizersOnExit已过时?.