0

I honestly can't figure it out - I've heard that thread.stop() is not a good thing to use. It also isn't working for me. How to get threads/handlers to stop running?

Alexander Farber
  • 21,519
  • 75
  • 241
  • 416
Hani Honey
  • 2,101
  • 11
  • 48
  • 76
  • Take a look at this: http://stackoverflow.com/questions/671049/how-do-you-kill-a-thread-in-java. – Malcolm May 07 '11 at 18:35

4 Answers4

5

Threads should be terminated in a "polite" way. You should build in some mechanism for your thread to stop. You can have a volatile boolean parameter that is checked on every loop of your thread (assuming you have loops in there) like so:

while (!threadStop) {
    // Do stuff
}

And then you can set the boolean value to false from another thread (make sure you handle all synchronization issues though) and your thread will stop in it's next iteration.

Savvas Dalkitsis
  • 11,476
  • 16
  • 65
  • 104
2

Ok the answer to stop threads have been done. To stop handler you have to use this following method :

removeCallbacksAndMessages from Handler class like this

myHandler.removeCallbacksAndMessages(null);
mrroboaat
  • 5,602
  • 7
  • 37
  • 65
  • This should be the chosen answer, just a little info. Check if your handler is not null before using the above. – User3 Dec 02 '14 at 06:21
-1

you can use it like this..

Thread mythread=new Thread();

if(!mythread){
    Thread dummy=mythread;
    mythread=null;
    dummy.interrupt();
}

or you can use

mythread.setDeamon(true);
keyser
  • 18,829
  • 16
  • 59
  • 101
-2

The correct way of stopping a handler is: handler.getLooper().quit();
I usually implement this by sending a quit message to handler which terminates itself.

The correct way of stopping a generic Thread is: thread.interrupt();
The thread that is being stopped needs to handle the interrupt:

if(isInterrupted())
    return;

This can be put in a loop if you wish:

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String line = null;
try {
    while(!isInterrupted() && (line = br.readLine()) != null) {
        // Do stuff with the line
    }
}
catch(IOException e) {
    // Handle IOException
}
catch(InterruptedException e) {
    // Someone called interrupt on the thread
    return;
}
Nicklas A.
  • 6,501
  • 7
  • 40
  • 65