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?

- 21,519
- 75
- 241
- 416

- 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 Answers
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.

- 11,476
- 16
- 65
- 104
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);

- 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
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);
-
What language is this? `if (!mythread)` will not work in Java. – Alexander Farber Jan 16 '17 at 15:51
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;
}

- 6,501
- 7
- 40
- 65