Stopping the threads

Starting a thread is very easy in java, after you create it you need to call the method start(), for example:

where MyRunnable is a class implementing the Runnable interface overidden the method run().

The creation of a thread using the constructor with argument a class implementing Runnable is one of two way to create a thread, the other is to extend the class Thread, and after you call the method start() to execute the thread.

Instead, stopping the thread is much more complicated, there is a method stop() but it is deprecated.

There are two ways to stop a thread:

  1. setting a flag
    consider a thread created with this Runnable:

    the field “running” is used in the method run() as condition to execute the loop, setting to false the method run() returns and the thread stops.
    In order to stop a thread with this Runnable you need the line:

    Note that the field “running” is volatile so that any thread accessing to “running” gets the latest value.
  2. calling the method interrupt()
    with the line:

    the thread is stopped at the first call of a method throwing the exception InterruptedException, for example wait(), join() and sleep(), as in the following:

    If no method throwing an InterruptedException is in the code then the you have to check if the method interrupt() is called:

One reply on “Stopping the threads”

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.