Hi, I'm new to 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?
- Use a flag: But the problem is what if resumeCalculating() takes (EDIT: 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?
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.