Stopping a Thread
Home ] Up ] Creating a Thread ] [ Stopping a Thread ] Extending the Thread Class ] Implementing Runnable ] An Example ]

 

 

You stop a thread by causing the thread to return from its run() execution.

Note: There is a stop() method in the Thread class, but its use is now deprecated, because it is inherently unsafe. DO NOT USE THIS METHOD!

For example, here is a typical run() method for a thread that will terminate after doing a finite amount of work:

public void run() 
{
   for (int i = 0; i < 100; i++) 
   {
      doWork();
   }
}

It simply terminates after a finite number of iterations through its work loop. Of course, the run() method is not required to loop at all; the thread may be doing one-time-only type work, and simply return when it has finished.

Some threads, once started, loop forever until some outside event causes them to terminate the loop. Here is how you typically write code to cause a thread to stop prematurely:

public class MyThreadOrRunnable ...
{
    ...

   public void run() 
   {
      while (m_running) 
      {
         doFiniteWork();
      }
   }

   public void stopExecution()
   {
      m_running = false;
   }

   private boolean m_running = true;
}

Note: Do not use the Thread's stop() method!

This is a simple case. If doWork() can take some time, and if you wish the thread to respond quickly to the request to stop its execution, then you must arrange for the code to check for the change of status on a regular basis.

Canceling an executing thread is a non-trivial exercise. For more details, see Doug Lea's "Cancelable Activities".  In general, Doug Lea's "Concurrent Programming in Java" is an excellent detailed reference for advanced use of threads in Java. See his Online Supplement.

 

The page was last updated February 19, 2008