[英]How should I terminate a looped sub-thread in Java?
當我要終止循環線程時,我需要做一些清理工作。 例如保存緩沖區,以便以后可以繼續。
PseudoCode:
private class CalculatePI(Byte[] resume) implements Runnable{
public void Run(){
while(true){
resume=resumeCalculating(resume);
}
}
}
Thread calculator= new Thread(new CalculatePI(Byte[] resume));
Thread.sleep(200);
//And now I want to kill calculator
那么實現此目標的最佳方法是什么?
所有者編輯:
我知道我可以使用標志。 但是考慮一下:
public void Run(){
while(true){
resume=calculate_stepone(resume); //takes one minute
resume=calculate_steptwo(resume); //takes two minutes
resume=calculate_stepthree(resume); //takes three minutes
resume=calculate_steplast(resume); //takes four minutes
}
}
正在放置一個if(flag) saveResultsAndExit();
每行之間實用還是漂亮? 我只想丟棄經過半處理的結果,並保存以前的結果。
停止線程的正確方法是中斷它。
如果線程中運行的任務正在執行IO或正在使用sleep
則它將接收到信號(此時為InterruptedException
); 否則,任務應定期輪詢以查看其是否中斷 。
讓我們修改原始海報的偽代碼:
private class CalculatePI(Byte[] resume) implements Runnable{
public void Run(){
while(!Thread.interrupted()) { //###
resume=resumeCalculating(resume);
}
}
}
Thread calculator= new Thread(new CalculatePI(Byte[] resume));
calculator.run(); //###
//...
//And now I want to kill calculator
calculator.interrupt(); //### sends the signal
//...
calculator.join(); //### actually waits for it to finish
對1的回答:您也可以在resumeCalculating()
處理中止標志。
最好使用一個標志,等待一段時間以使線程結束,如果沒有結束(resumeCalculating尚未返回),則手動終止該線程。 最好不要在簡歷計算中包含太多基於線程的邏輯,這實際上取決於實現方式以及中途中止操作的容易程度。
設計您的程序,以使resumeCalculation不會永遠花費下去。 另外,同步訪問您的標志。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.