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. Use a flag: But the problem is what if resumeCalculating() takes (EDIT: 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?

EDIT by Owner:

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
       }
    }

```

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.