The Java Developers Almanac 1.4


Order this book from Amazon.

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

e96. Pausing a Thread

The proper way to temporarily pause the execution of another thread is to set a variable that the target thread checks occasionally. When the target thread detects that the variable is set, it calls Object.wait(). The paused thread can then be woken up by calling its Object.notify() method.

Note: Thread.suspend() and Thread.resume() provide methods for pausing a thread. However, these methods have been deprecated because they are very unsafe. Using them often results in deadlocks. With the approach above, the target thread can ensure that it will be paused in an appropriate place.

    // Create and start the thread
    MyThread thread = new MyThread();
    thread.start();
    
    while (true) {
        // Do work
    
        // Pause the thread
        synchronized (thread) {
            thread.pleaseWait = true;
        }
    
        // Do work
    
        // Resume the thread
        synchronized (thread) {
            thread.pleaseWait = false;
            thread.notify();
        }
    
        // Do work
    }
    
    class MyThread extends Thread {
        boolean pleaseWait = false;
    
        // This method is called when the thread runs
        public void run() {
            while (true) {
                // Do work
    
                // Check if should wait
                synchronized (this) {
                    while (pleaseWait) {
                        try {
                            wait();
                        } catch (Exception e) {
                        }
                    }
                }
    
                // Do work
            }
        }
    }

 Related Examples
e92. Creating a Thread
e93. Stopping a Thread
e94. Determining When a Thread Has Finished
e95. Pausing the Current 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.