I google the solution for killing a java thread. And there exists two solutions:
set a flag
using 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.
So how can I kill this thread ? Thanks in advance.
解决方案
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.
博主谷歌了终止Java线程的方法,有设置标志和使用Thread.interrupt两种,但因线程中调用耗时第三方API,这两种不适用,博主希望用户能在耗时过长时取消线程。解决方案指出Thread.interrupt()是通用安全方法,也可用应用级信号自终止。

被折叠的 条评论
为什么被折叠?



