[英]killing a running thread in java?
如何在Java中杀死正在运行的线程
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 . 请注意,还存在其他一些具有类似语义的方法-stop
stop()
和destroy()
-,但不赞成使用它们,因为它们不安全 。 Don't be tempted to use them. 不要试图使用它们。
As Bozho said, Thread.interrupt() is the generic and right way to do it. 正如Bozho所说,Thread.interrupt()是执行此操作的通用且正确的方法。 But remember that it requires the thread to cooperate;
但是请记住,这需要线程进行合作; It is very easy to implement a thread that ignores interruption requests.
实现一个忽略中断请求的线程非常容易。
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()). 为了使一段代码可以这种方式被中断,它不应忽略任何InterruptedException,并且应在每次循环迭代时检查中断标志(使用Thread.currentThread()。isInterrupted())。 Also, it shouldn't have any non-interruptible blocking operations.
而且,它不应该有任何不间断的阻塞操作。 If such operations exist (eg waiting on a socket), then you'll need a more specific interruption implementation (eg closing the socket).
如果存在此类操作(例如,在套接字上等待),则需要更具体的中断实现(例如,关闭套接字)。
Shortly you need Thread.interrupt()
不久您需要
Thread.interrupt()
For more details check the section How do I stop a thread that waits for long periods (eg, for input)
in this article Why Are Thread.stop
, Thread.suspend
, Thread.resume
and Runtime.runFinalizersOnExit
Deprecated? 有关更多详细信息,请参阅本文中的
How do I stop a thread that waits for long periods (eg, for input)
部分。 为什么Thread.resume
使用Thread.stop
, Thread.suspend
, Thread.resume
和Runtime.runFinalizersOnExit
? . 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.