Stopping a Thread


public class StoppableThread extends Thread {    private boolean done = false;    public void run( ) {       while (!done) {          System.out.println("Thread running");          try {             sleep(500);          }          catch (InterruptedException ex) {             // do nothing          }       }       System.out.println("Thread finished.");    }    public void shutDown( ) {       done = true;    } }



If you want to create a thread that you can stop at some point prior to the completion of its executionthat is, the return from the run() methodthe best way to do this is to use a boolean flag that you test at the top of a main loop. In this phrase, we create a thread by extending the THRead class with our StoppableThread class. Within the run() method, we have a while loop that checks the status of a boolean done flag. As long as the done flag remains false, the thread continues. To stop the thread, an external process could set the done flag to true, and this would cause the while loop in the run() method to exit and thus terminate this thread.

The THRead class does contain a stop() method, which some might be tempted to use to stop the thread, but Sun actually recommends against using this method. The reason is this: In case your thread is operating on any of your data structure objects and you suddenly call stop() on the thread, the objects will be left in an inconsistent state. In case any of your other threads are waiting for this particular object to be released, they will get stuck waiting forever. This might eventually lead to a deadlock situation. Also, the stop() method is deprecated in JDK 1.2 and later, so if you do use the stop() method in one of these JDKs, the compiler will generate deprecation warnings.

A good reference to the reasons why stop() is deprecated can be found here: http://java.sun.com/j2se/1.5.0/docs/guide/misc/threadPrimitiveDeprecation.html




JavaT Phrasebook. Essential Code and Commands
Java Phrasebook
ISBN: 0672329077
EAN: 2147483647
Year: 2004
Pages: 166

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net