Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you kill a Thread in Java?

How do you kill a java.lang.Thread in Java?

like image 987
flybywire Avatar asked Mar 22 '09 14:03

flybywire


People also ask

How do you stop a 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.

Can I kill thread?

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.

How do you end a thread?

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!


2 Answers

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.

like image 180
JaredPar Avatar answered Nov 02 '22 23:11

JaredPar


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)

like image 31
Fredrik Avatar answered Nov 03 '22 00:11

Fredrik