There might be times when you need to temporarily stop a thread from processing and then resume processing, such as when you want to let another thread use the current resource. You can achieve this objective by defining your own suspend and resume methods, as shown in the following example.
This example defines a MyThread class. The MyThread class defines three methods: the run() method, the suspendThread() method, and the resumeThread() method. In addition, the MyThread class declares the instance variable suspended , whose value is used to indicate whether or not the thread is suspended.
The run() method contains a for loop that displays the value of the counter variable. Each time the counter variable is displayed, the thread pauses briefly. It then enters a synchronized statement to determine whether the value of the suspended instance variable is true. If so, the wait() method is called, causing the thread to be suspended until the notify() method is called.
The suspendThread() method simply assigns true to the suspended instance variable. The resumeThread() method assigns false to the suspended instance variable and then calls the notify() method. This causes the thread that is suspended to resume processing.
The main() method of the Demo class declares an instance of MyThread and then pauses for about a second before calling the suspendThread() method and displaying an appropriate message on the screen. It then pauses for about another second before calling the resumeThread() method and again displaying an appropriate message on the screen.
The thread continues to display the value of the counter variable until the thread is suspended. The thread continues to display the value of the counter variable once the thread resumes processing. Here’s what is displayed when you run this program:
Thread: 0
Thread: 1
Thread: 2
Thread: 3
Thread: 4
Thread: Suspended
Thread: Resume
Thread: 5
Thread: 6
Thread: 7
Thread: 8
Thread: 9
Thread exiting.
class MyThread implements Runnable {
String name;
Thread t;
boolean suspended;
MyThread() {
t = new Thread(this, "Thread");
suspended = false ;
t.start();
}
public void run() {
try {
for (int i = 0; i < 10; i++) {
System.out.println("Thread: " + i );
Thread.sleep(200);
synchronized (this) {
while (suspended) {
wait();
}
}
}
} catch (InterruptedException e ) {
System.out.println("Thread: interrupted.");
}
System.out.println("Thread exiting.");
}
void suspendThread() {
suspended = true;
}
synchronized void resumeThread() {
suspended = false;
notify();
}
}
class Demo {
public static void main (String args [] ) {
MyThread t1 = new MyThread();
try{
Thread.sleep(1000);
t1.suspendThread();
System.out.println("Thread: Suspended");
Thread.sleep(1000);
t1.resumeThread();
System.out.println("Thread: Resume");
} catch ( InterruptedException e) {
}
try {
t1.t.join();
} catch ( InterruptedException e) {
System.out.println (
"Main Thread: interrupted");
}
}
}