How do you kill a java.lang.Thread
in Java?
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- SQL join to get the cartesian product of 2 columns
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
One way is by setting a class variable and using it as a sentinel.
Set an external class variable, i.e. flag = true in the above example. Set it to false to 'kill' the thread.
I'd vote for
Thread.stop()
.As for instance you have a long lasting operation (like a network request). Supposedly you are waiting for a response, but it can take time and the user navigated to other UI. This waiting thread is now a) useless b) potential problem because when he will get result, it's completely useless and he will trigger callbacks that can lead to number of errors.
All of that and he can do response processing that could be CPU intense. And you, as a developer, cannot even stop it, because you can't throw
if (Thread.currentThread().isInterrupted())
lines in all code.So the inability to forcefully stop a thread it weird.
There is no way to gracefully kill a thread.
You can try to interrupt the thread, one commons strategy is to use a poison pill to message the thread to stop itself
}
http://anandsekar.github.io/cancel-support-for-threads/
I want to add several observations, based on the comments that have accumulated.
Generally you don't..
You ask it to interrupt whatever it is doing using Thread.interrupt() (javadoc link)
A good explanation of why is in the javadoc here (java technote link)
See this thread by Sun on why they deprecated
Thread.stop()
. It goes into detail about why this was a bad method and what should be done to safely stop threads in general.The way they recommend is to use a shared variable as a flag which asks the background thread to stop. This variable can then be set by a different object requesting the thread terminate.