Suspending, Resuming, and Stopping Threads
The following example illustrates how the wait( ) and notify( ) methods that are inherited from Object can be used to control the execution of a thread.
class NewThread implements Runnable {
String name; // name of thread
Thread t;
boolean suspendFlag = false;
NewThread(String threadname) {
name = threadname;
t = new Thread(this, name);
t.start(); // Start the thread
}
public void run() {
try {
for (int i = 5; i > 0; i--) {
System.out.println(name + ": " + i);
Thread.sleep(500);
synchronized (this) {
while (suspendFlag) {
wait();
}
}
}
} catch (InterruptedException e) {
System.out.println(name + " interrupted.");
}
System.out.println(name + " exiting.");
}
void suspend() {
suspendFlag = true;
}
synchronized void resume() {
suspendFlag = false;
notify();
}
}
public class Main {
public static void main(String args[]) throws Exception {
NewThread ob1 = new NewThread("One");
NewThread ob2 = new NewThread("Two");
Thread.sleep(1000);
ob1.suspend();
Thread.sleep(2000);
ob1.resume();
ob2.suspend();
Thread.sleep(3000);
ob2.resume();
}
}