views:

3847

answers:

6

How do you kill a thread in Java?

+13  A: 

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.

JaredPar
+3  A: 

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.

Fredrik
+1 for agreeance with sgreeve
JaredPar
+2  A: 

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.

karim79
This isn't reliable; make "flag" `volatile` to ensure it works properly everywhere. The inner class is not static, so the flag should an instance variable. The flag should be cleared in an accessor method so that other operations (like interrupt) can be performed. The name "flag" is not descriptive.
erickson
A: 

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.

ReneS
A: 

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 :(

sofia
A: 

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.

Gorka Siverio