java 如何杀死一个java线程?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4121470/
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
How to kill a java thread?
提问by zjffdu
I google the solution for killing a java thread. And there exists two solutions:
我在谷歌上搜索了杀死 Java 线程的解决方案。并且存在两种解决方案:
- set a flag
- using Thread.interrupt
- 立旗
- 使用 Thread.interrupt
But both of them are not suitable for me. In my thread, I call a third-party api which takes a long time to complete. and I want to let the user to cancel this thread if it takes too much time.
但是两者都不适合我。在我的线程中,我调用了一个需要很长时间才能完成的第三方api。如果需要太多时间,我想让用户取消此线程。
So how can I kill this thread ? Thanks in advance.
那么我怎样才能杀死这个线程呢?提前致谢。
回答by Yann Ramin
Thread.interrupt()
is the only safe method which is generally applicable. You can of course use other application-level signals (such as a conditional check on a volatile variable) to self-terminate. Other methods (such as all the deprecated Thread.xx methods) can pollute your application's state in non-deterministic ways, and would require reloading all application state.
Thread.interrupt()
是唯一普遍适用的安全方法。您当然可以使用其他应用程序级信号(例如对 volatile 变量的条件检查)来自我终止。其他方法(例如所有已弃用的 Thread.xx 方法)可能会以不确定的方式污染应用程序的状态,并且需要重新加载所有应用程序状态。
回答by Stephen C
In theory, you could call the deprecated Thread.stop()
method. But beware that this could result in your application behaving in unexpected and unpredictable ways ... depending on what the third party library is actually doing. Thread.stop()
and friends are fundamentally unsafe.
理论上,您可以调用已弃用的Thread.stop()
方法。但请注意,这可能会导致您的应用程序以意外和不可预测的方式运行……这取决于第三方库的实际操作。 Thread.stop()
和朋友从根本上是不安全的。
The best solution is to modify the 3rd-party library to respond to Thread.interrupt. If you cannot, then ditch it and find / use a better library.
最好的解决办法是修改3rd-party库来响应Thread.interrupt。如果你不能,那就放弃它并找到/使用更好的库。
回答by user454322
I would put the call a third-party api which takes a long timeinto a Callable<DataTypeReturnedBy3rdPartAPI>
and then execute it with a SingleThreadExecutor
specifying a timeout.
我会把调用第三方API,它需要很长的时间进入Callable<DataTypeReturnedBy3rdPartAPI>
,然后用执行它SingleThreadExecutor
指定一个超时。
Following this approach, the thread will be killedif the call to third party APItakes longer than timeOut
, here is some code to exemplify what I am saying:
按照这种方法,如果调用第三方 API的时间超过,线程将被终止,这里有一些代码来举例说明我在说什么:timeOut
ExecutorService executor = Executors.newSingleThreadExecutor();
try {
//================= HERE ==================
Future<Boolean> job = executor.submit(thirdPartyCallable);
executor.awaitTermination(timeOut, TimeUnit.SECONDS);
if(!job.isDone())
logger.debug("Long call to 3rd party API didn't finish");
//=========================================
} catch (Exception exc) {
exc.printStackTrace();
} finally {
if(!executor.isShutdown() )
executor.shutdownNow();
}
}
private static Callable<Boolean> thirdParytCallable = new Callable<Boolean>() {
public Boolean call() throws Exception {
//Call to long 3rd party API
//.......
for(long i = 0;i<99999991999999L;i++) {
Thread.sleep(10L);// Emulates long call to 3rd party API
System.out.print(".");
}
return Boolean.valueOf(true);//Data from 3rd party API
}
};
回答by verisimilidude
Spawn a separate process and kill it using OS facilities. You'll have to call into "C" to do it but it won't be much code. You didn't say what OS you are running on.
生成一个单独的进程并使用操作系统工具杀死它。您必须调用“C”才能执行此操作,但这不会是太多代码。你没有说你正在运行什么操作系统。
回答by Mike Lue
In java.util.concurrent.FutureTask, the mechanism of cancellation by timeout is acted as throwing java.util.concurrent.TimeoutException.
在java.util.concurrent.FutureTask 中,超时取消机制相当于抛出java.util.concurrent.TimeoutException。
You may check out this as if there are something to be interrupted automatically by timeout.
你可以检查一下,好像有什么东西会被超时自动中断。
回答by Joeri Hendrickx
Since Thread.stop()
is (rightly) deprecated, generally this is accomplished by setting a flag to true. Something like this:
由于Thread.stop()
(正确地)已弃用,通常这是通过将标志设置为 true 来实现的。像这样的东西:
Calling Class:
调用类:
...
workListExecutor.stop()
...
WorkListExecutor.class:
WorkListExecutor.class:
boolean running = true;
void stop(){
running = false;
}
void run(){
while (running) {
... do my stuff ...
}
}
This is assuming your thread has some kind of main loop (usually the case).
If the code in your loop is too big, you can periodically check if running
is still true
, and bail out if it's not.
这是假设您的线程具有某种主循环(通常是这种情况)。如果循环中的代码太大,您可以定期检查是否running
仍然是true
,如果不是,则退出。
This has the advantage that you can still clean up when you're done. The thread will be killed automatically when your run method finishes.
这样做的好处是您在完成后仍然可以进行清理。当您的 run 方法完成时,线程将自动终止。
回答by vanza
You can try Thread.stop(), but at your own risk. Optimally, the API you're calling should have a way to interrupt the operation if needed (which is what Thread.interrupt()is for if the API itself does not provide a cleaner way to interrupt its progress, have you tried it?).
您可以尝试Thread.stop(),但风险自负。最佳情况下,您正在调用的 API 应该有一种方法可以在需要时中断操作(如果 API 本身没有提供更简洁的方法来中断其进程,这就是Thread.interrupt()的用途,您尝试过吗?) .
回答by sasuke
You can invoke the stop
method on the Thread object but it is strongly recommended that you don't. Read this: http://download.oracle.com/javase/1.5.0/docs/guide/misc/threadPrimitiveDeprecation.html
您可以调用stop
Thread 对象上的方法,但强烈建议您不要。阅读:http: //download.oracle.com/javase/1.5.0/docs/guide/misc/threadPrimitiveDeprecation.html
Do you have the freedom to make minor changes to the API? Is this blocking call CPU bound or IO bound? If it is IO bound and if you have access to the underlying socket/remote communication object, closing that object can do wonders. It is at least better than stoppingthe thread.
您可以自由地对 API 进行细微的更改吗?这个阻塞调用是 CPU 绑定还是 IO 绑定?如果它是 IO 绑定的,并且您可以访问底层套接字/远程通信对象,那么关闭该对象会产生奇迹。至少比停止线程要好。