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?
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.
The proper way to stop a thread is to interrupt it.
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