如何在Android中停止线程和处理程序

时间:2011-05-07 18:32:22

标签: android handler

老实说,我无法弄清楚 - 我听说thread.stop()不是一件好事。它也不适合我。如何让线程/处理程序停止运行?

4 个答案:

答案 0 :(得分:5)

线程应该以“礼貌”的方式终止。你应该建立一些机制让你的线程停止。你可以在你的线程的每个循环上检查一个volatile布尔参数(假设你有循环),如下所示:

while (!threadStop) {
    // Do stuff
}

然后你可以从另一个线程将boolean值设置为false(确保你处理所有同步问题),你的线程将在下一次迭代中停止。

答案 1 :(得分:2)

好的,停止线程的答案已经完成。要停止处理程序,您必须使用以下方法:

removeCallbacksAndMessages from Handler class喜欢这个

myHandler.removeCallbacksAndMessages(null);

答案 2 :(得分:-1)

你可以像这样使用..

Thread mythread=new Thread();

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

或 你可以用

mythread.setDeamon(true);

答案 3 :(得分:-2)

停止处理程序的正确方法是: handler.getLooper().quit();
我通常通过向处理程序发送退出消息来实现此目的,该处理程序终止自身。

停止通用线程的正确方法是: thread.interrupt();
正在停止的线程需要处理中断:

if(isInterrupted())
    return;

如果您愿意,可以将其置于循环中:

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