I google the solution for killing a java thread. And there exists two solutions:
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With