How do you kill a thread in Java?
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.
http://java.sun.com/j2se/1.4.2/docs/guide/misc/threadPrimitiveDeprecation.html
The way they recomend 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().
A good explanation of why is in the javadoc: http://java.sun.com/j2se/1.5.0/docs/guide/misc/threadPrimitiveDeprecation.html
Edit: 18 seconds late to be first reply... damn.
One way is by setting a class variable and using it as a sentinel.
Class Outer
{
public static flag = true;
Outer()
{
new Test().start();
}
class Test extends Thread
{
public void run()
{
while(Outer.flag)
{
//do stuff here
}
}
}
}
Set an external class variable, i.e. flag = true in the above example. Set it to false to 'kill' the thread.
Just as a side hint: A variable as flag only works, when the thread runs and it is not stuck. Thread.interrupt() should free the thread out of most waiting conditions (wait, sleep, network read, and so on). Therefore you should never never catch the InterruptedException to make this work.
I don't get the "while" thing in the run method. Doesn't this mean that whatever is written in the run method will be being repeated? this is not something we wanted the thread to do in the first place :(
Yes, Sofia. But, besides that, now we want to handle the while's condition, so that we can set it false whenever we want to.