Skip to Main Content
Java Cookbook
book

Java Cookbook

by Ian F. Darwin
June 2001
Intermediate to advanced content levelIntermediate to advanced
888 pages
21h 1m
English
O'Reilly Media, Inc.
Content preview from Java Cookbook

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. ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Practical Cloud-Native Java Development with MicroProfile

Practical Cloud-Native Java Development with MicroProfile

Emily Jiang, Andrew McCright, John Alcorn, David Chan, Alasdair Nottingham
Distributed Computing in Java 9

Distributed Computing in Java 9

Raja Malleswara Rao Malleswara Rao Pattamsetti

Publisher Resources

ISBN: 0596001703Supplemental ContentCatalog PageErrata