Is it possible to interrupt a running thread? InterruptedException is only thrown if the thread is interrupted while in the sleep state and calling interrupt() on a running thread has no effect.

Larry Widing

[More info from the questioner:

Consider a long running task that is not loop based. How can you "cancel" the task before it reaches the end of the run() method and without having to check a boolean active flag on each line of run()?

Consider:

public void run() {
  try {
    // long-running, non-repetitive task
  }
  catch(InterruptedException e) {
    // handle the interruption or cancel
  }
}

As intuitive as this seems, the InterruptedException is only thrown if the thread is interrupted while in the sleep state and calling interrupt() on a running thread has no effect. I'd like a way to interrupt a running thread.]

It is best to not rely on this feature, as it does not always work, even if the thread is in a sleep state. I have found that several versions of Netscape completely ignore Thread.interrupt(). For this reason, the only truly effective means to stop a running thread is to use a combination of locks and state flags.

I know this is not an ideal answer, but there really is not one available for this issue. Use something along the lines of:


class Test extends Thread
{
   boolean stopThis = false;
   public void run()
   {
      while (!getStopThis())
      {
         // some operations

         // insert the following at various points
         // in the thread processing.
         if (getStopThis())
            break;         
      }
   }

   public boolean getStopThis()
   {
      return stopThis;
   }

   public void stopThisNow()
   {
      stopThis = true;
   }
}

You will need to balance the number of times you call getStopThis(), as synchronized calls can quickly become a major performance bottleneck. Therefore, in a situation like this it becomes important to balance performance with responsiveness to a request to stop the thread. [Note: the accessor methods do not need to be synchronized, since boolean set/get are guaranteed to be atomic. This removes the performance problems, but still leads to more complicated code, and you may still end up waiting quite a while between the "stopThisNow()" call and the time when the thread actually stops.]

I usually put such calls before anything that might perform some kind of I/O (updating the display, writing to a file, reading from a file, etc).

See also How do I properly stop a running thread, now that Thread.stop() has been deprecated?.

0 Comments  (click to add your comment)
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

About | Sitemap | Contact