Here is a Java Program to Suspending and resuming a thread
Output of Above Java Program
New thread: Thread[One,5,main]
New thread: Thread[Two,5,main]
One: 15
Two: 15
Two: 14
One: 14
One: 13
Two: 13
Two: 12
One: 12
One: 11
Two: 11
One: 10
Two: 10
Suspending thread One
Two: 9
Two: 8
Two: 7
Two: 6
Resuming thread One
One: 9
Suspending thread Two
One: 8
One: 7
One: 6
One: 5
Two: 5
Resuming thread Two
One: 4
Waiting for threads to finish.
Two: 4
One: 3
One: 2
Two: 3
One: 1
Two: 2
Two: 1
One exiting.
Two exiting.
Main thread exiting.
class NewThread implements Runnable {
String name; // name of thread
Thread t;
boolean suspendFlag;
NewThread(String threadname) {
name = threadname;
t = new Thread(this, name);
System.out.println("New thread: " + t);
suspendFlag = false;
t.start(); // Start the thread
}
// 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(suspendFlag) {
wait();
}
}
}
} catch (InterruptedException e) {
System.out.println(name + " interrupted.");
}
System.out.println(name + " exiting.");
}
void mysuspend() {
suspendFlag = true;
}
synchronized void myresume() {
suspendFlag = false;
notify();
}
}
class SuspendResume {
public static void main(String args[]) {
NewThread ob1 = new NewThread("One");
NewThread ob2 = new NewThread("Two");
try {
Thread.sleep(1000);
ob1.mysuspend();
System.out.println("Suspending thread One");
Thread.sleep(1000);
ob1.myresume();
System.out.println("Resuming thread One");
ob2.mysuspend();
System.out.println("Suspending thread Two");
Thread.sleep(1000);
ob2.myresume();
System.out.println("Resuming thread Two");
} catch (InterruptedException e) {
System.out.println("Main thread Interrupted");
}
// wait for threads to finish
try {
System.out.println("Waiting for threads to finish.");
ob1.t.join();
ob2.t.join();
} catch (InterruptedException e) {
System.out.println("Main thread Interrupted");
}
System.out.println("Main thread exiting.");
}
}
Output of Above Java Program
New thread: Thread[One,5,main]
New thread: Thread[Two,5,main]
One: 15
Two: 15
Two: 14
One: 14
One: 13
Two: 13
Two: 12
One: 12
One: 11
Two: 11
One: 10
Two: 10
Suspending thread One
Two: 9
Two: 8
Two: 7
Two: 6
Resuming thread One
One: 9
Suspending thread Two
One: 8
One: 7
One: 6
One: 5
Two: 5
Resuming thread Two
One: 4
Waiting for threads to finish.
Two: 4
One: 3
One: 2
Two: 3
One: 1
Two: 2
Two: 1
One exiting.
Two exiting.
Main thread exiting.