如何终止Java中的循环子线程? [英] How should I terminate a looped sub-thread in Java?
问题描述
当我要终止循环线程时,我需要做一些清理工作.例如保存缓冲区,以便以后再继续.
I need to do some clean up work when I am going to terminate a looped thread. Such as saving a buffer so I can continue later.
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
那么实现此目标的最佳方法是什么?
So what's the best way implement this?
- 使用标志:但是问题是,如果resumeCalculating()需要(很长时间)
永远结束? - 将异常放入计算器,如何?
- 我可以使用事件侦听器或其他方法吗?我以为它们用于GUI
- 停下来吗?并且Class Thread包含某种解构函数,当线程终止时会被调用,我可以在那里进行处理吗?
- Use a flag: But the problem is what if resumeCalculating() takes ( a long time)
foreverto end? - Put an exception into calculator, how?
- Can I use event listeners or something? I thought they were used for GUIs
- Just stop it? And Class Thread includes some kind of deconstructor that will be called when the thread is terminated and I could do the processing there?
所有者
我知道我可以使用标志.但是请考虑一下:
I know I can use a flag. But consider this:
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();
是实用的还是漂亮的?
我只想丢弃经过半处理的结果,并保存以前的结果.
Is putting a if(flag) saveResultsAndExit();
between every line practical or pretty?
I just want to throw away the half-processed results, and save the previous results.
推荐答案
The proper way to stop a thread is to interrupt it.
如果线程中运行的任务正在执行IO或正在使用sleep
,则它将接收到信号(此时为InterruptedException
);否则,任务应定期轮询以查看其已中断.
If the task running in the thread is performing IO or is using sleep
then it will receive the signal (InterruptedException
at that point); else the task should regularly poll to see if its interrupted.
让我们修改原始海报的伪代码:
Lets adapt the original poster's psuedocode:
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
这篇关于如何终止Java中的循环子线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!