How do you kill a java.lang.Thread
in Java?
Whenever we want to stop a thread from running state by calling stop() method of Thread class in Java. This method stops the execution of a running thread and removes it from the waiting threads pool and garbage collected. A thread will also move to the dead state automatically when it reaches the end of its method.
You should never forcibly kill a thread without cooperating with it. Killing a thread removes any guarantees that try/finally blocks set up so you might leave locks locked, files open, etc.
Pull gently on the thread and you'll see a loop forming. Pass your needle through the loop and begin to pull. Keep pulling until the loop entirely flattens out. Cut off the tail end and you're done!
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.
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)
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