The Java Developers Almanac 1.4


Order this book from Amazon.

   
Home > List of Packages > java.lang  [58 examples] > Threads  [11 examples]

e93. Stopping a Thread

The proper way to stop a running thread is to set a variable that the thread checks occasionally. When the thread detects that the variable is set, it should return from the run() method.

Note: Thread.suspend() and Thread.stop() provide asynchronous methods of stopping a thread. However, these methods have been deprecated because they are very unsafe. Using them often results in deadlocks and incorrect resource cleanup.

    // Create and start the thread
    MyThread thread = new MyThread();
    thread.start();
    
    // Do work...
    
    // Stop the thread
    thread.allDone = true;
    
    class MyThread extends Thread {
        boolean allDone = false;
    
        // This method is called when the thread runs
        public void run() {
            while (true) {
                // Do work...
    
                if (allDone) {
                    return;
                }
    
                // Do work...
            }
        }
    }

 Related Examples
e92. Creating a Thread
e94. Determining When a Thread Has Finished
e95. Pausing the Current Thread
e96. Pausing a Thread
e97. Determining If the Current Thread Is Holding a Synchronized Lock
e98. Allowing an Application with Live Threads to Exit
e99. Listing All Running Threads
e100. Using a Thread-Local Variable
e101. Getting the Stack Trace of an Exception
e102. Implementing a Work Queue

See also: Arrays    Assertions    Classes    Commands    Numbers    Objects    Strings    System Properties   


© 2002 Addison-Wesley.