Search code examples
javamultithreadingterminate

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?

  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.


Solution

  • 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