2011-05-07 109 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