Java Reference
In-Depth Information
thread will remain suspended because there is no one who will resume it, and the thread that will resume it will
remain blocked because the monitor lock it is trying to obtain is held by the suspended thread. This is the reason
that the suspend() method has been deprecated. The resume() method is also deprecated because it is called in
conjunction with the suspend() method. You can use a similar technique to simulate the suspend() and resume()
methods of the Thread class in your program as you did to simulate the stop() method.
Listing 6-25 demonstrates how to simulate the stop() , suspend() , and resume() methods of the Thread class in
your thread.
Listing 6-25. Stopping, Suspending, and Resuming a Thread
// StopSuspendResume.java
package com.jdojo.threads;
public class StopSuspendResume extends Thread {
private volatile boolean keepRunning = true;
private boolean suspended = false;
public synchronized void stopThread() {
this.keepRunning = false;
// Notify the thread in case it is suspended when this method
// is called, so it will wake up and stop.
this.notify();
}
public synchronized void suspendThread() {
this.suspended = true;
}
public synchronized void resumeThread() {
this.suspended = false;
this.notify();
}
public void run() {
System.out.println("Thread started...");
while (keepRunning) {
try {
System.out.println("Going to sleep...");
Thread.sleep(1000);
// Check for a suspended condition must be made inside a
// synchronized block to call the wait() method
synchronized (this) {
while (suspended) {
System.out.println("Suspended...");
this.wait();
System.out.println("Resumed...");
}
}
}
Search WWH ::




Custom Search