2011-05-07 62 views

回答

5

线程应以“礼貌”的方式终止。你应该建立一些机制让你的线程停下来。你可以是你的线程的每个循环中检查挥发性布尔参数(假设你有循环在那里),像这样:

while (!threadStop) { 
    // Do stuff 
} 

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

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

不应该使用Thread.interrupt()。见上面的评论。 – Moritz 2011-12-29 11:34:24

-1

,你可以使用它像这样..

Thread mythread=new Thread(); 

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

或 可以使用

mythread.setDeamon(true); 
+0

这是什么语言? 'if(!mythread)'在Java中不起作用。 – 2017-01-16 15:51:04

2

确定的答案,停止线程已经完成。要停止处理程序,你必须使用此方法如下:

removeCallbacksAndMessages from Handler class这样

myHandler.removeCallbacksAndMessages(null); 
+0

这应该是选择的答案,只是一些信息。在使用上述内容之前检查你的处理程序是否为空。 – User3 2014-12-02 06:21:56