如何终止Java中的循环子线程? [英] How should I terminate a looped sub-thread in Java?

查看:103
本文介绍了如何终止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?

  1. 使用标志:但是问题是,如果resumeCalculating()需要(很长时间)永远结束?
  2. 将异常放入计算器,如何?
  3. 我可以使用事件侦听器或其他方法吗?我以为它们用于GUI
  4. 停下来吗?并且Class Thread包含某种解构函数,当线程终止时会被调用,我可以在那里进行处理吗?
  1. Use a flag: But the problem is what if resumeCalculating() takes ( a long time) forever to end?
  2. Put an exception into calculator, how?
  3. Can I use event listeners or something? I thought they were used for GUIs
  4. 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆