Suspending and resuming a thread:
The NewThread class holds a boolean object variable named supendFlag, that is used to control the execution of the thread. This is initialized to false through the constuctor. The run ( ) method holds a synchronized statement block which checks suspendFlag. IF that variable is true, the wait ( ) functions is invoked to suspend the execution of the thread. A mysuspend ( ) method sets suspendFlag to true. The myresume ( ) method set suspendFlag to false and invokes notify ( ) to wake up the thread. At last, the main ( ) method has been changed to invoke the suspend () and, myresume ( ) methods.
// suspending and resuming a thread for java 2
class NewThread implements Runnable
{
String n; Thread t; boolean s;
NewThread(String tn) {
n= threadname;
t=new Thread(this, n);
System.out.println("New thread: " +t);
s=false;
t.start();
}
//This is the entry point for thread.
public void run() {
try{
for(int i= 15; i> 0; i--){
System.out.println(name " ";"+i);
Thread.sleep(200);
synchronized(this){
while(s) {
wait();
}
}
}
}catch(InterruptedException e)
System.out.println(name+" interrupted.");
}
System.out.println(name+" exiting.");
}
void mysuspend(){
s=true;
}
synchornized void myresume() {
s=false;
notify();
}
}
class SuspendResume {
public static void main(String a[])
NewThread o1 = new NewThread("one");
NewThread o2 = new NewThread("Two");
try {
Thread.sleep(1000);
o1.mysuspend();
System.out.println("Suspending thread One");
Thread.sleep(1000);
o1.myresume();
System.out.println("Resuming thread One");
o2.mysuspend();
System.out.println("Suspending thread Two");
Thread.sleep(1000);
o2.myresume();
System.out.println("Resuming thread Two");
} catch(InterruptedException e) {
System.out.println("Main thread Interrupted");
}
// wait fot thread to finish try {
System.out.println("waiting for threads to finish");
o1.t.join();
o2.t.join();
}catch(InterruptedException e) {
System.out.println("Main thread interrupted");
}
System.out.println("Main thread Exiting");
}
}
Although this mechanism is not as "clean" as the previous way, yet, it is the way needed to ensure in which run-time errors don't occur. It is the approach which must be used to all new code.