O'Reilly logo

Java Cookbook by Ian F. Darwin

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Stopping a Thread

Problem

You need to stop a thread.

Solution

Don’t use the Thread.stop( ) method; instead, use a boolean tested at the top of the main loop in the run( ) method.

Discussion

While you can use the thread’s stop( ) method, Sun recommends against it. That’s because the method is so drastic that it can never be made to behave reliably in a program with multiple active threads. That is why, when you try to use it, the compiler will generate deprecation warnings. The recommended method is to use a boolean variable in the main loop of the run( ) method. The program in Example 24-5 prints a message endlessly until its shutDown( ) method is called; it then sets the controlling variable done to false, which terminates the loop. This causes the run( ) method to return, ending the thread. The ThreadStoppers program in the source directory for this chapter has a main program that instantiates and starts this class, and then calls the shutDown( ) method.

Example 24-5. StopBoolean.java

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

Running it looks like this:

StopBoolean running StopBoolean running StopBoolean running StopBoolean running StopBoolean running StopBoolean running StopBoolean running StopBoolean finished. ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required