How to stop threads and handlers in Android

十年热恋 提交于 2019-12-14 03:15:03

问题


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?


回答1:


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.




回答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);



回答3:


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);



回答4:


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;
}


来源:https://stackoverflow.com/questions/5923159/how-to-stop-threads-and-handlers-in-android

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!