Suspending, Resuming, and Stopping Threads
These are the methods defined by Thread, to pause, restart, and stop the execution of a thread.
In java2 these methods are disapproved as if the suspend() method pause the thread which locks a critical data then it will not be unlocked in future.
The method resume() don't have use if there is no suspend() method.
stop() is due to stopping of a thread which performing some action in progress.
Instead of using these methods we have different ways to control the execution of Threads.
// Suspending and resuming a thread the modern way.
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 = 9; 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.");
}
synchronized void mysuspend() {
suspendFlag = true;
}
synchronized void myresume() {
suspendFlag = false;
notify();
}
}
public 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:
New thread: Thread[One,5,main]
New thread: Thread[Two,5,main]
One: 9
Two: 9
One: 8
Two: 8
One: 7
Two: 7
One: 6
Two: 6
One: 5
Two: 5
Suspending thread One
Two: 4
Two: 3
Two: 2
Two: 1
Two exiting.
Resuming thread One
Suspending thread Two
One: 4
One: 3
One: 2
One: 1
One exiting.
Resuming thread Two
Waiting for threads to finish.
Main thread exiting.
Obtaining A Thread’s State
We can get a current state of a thread by calling getThread() method.
Definition of getState() is::
Thread.State getState( )
This methods returns the value of type Thread.State which indicates the current state of the thread.
State is the enumeration defined by Thread.
getState() will returns the following values as states::
Diagram to show the thread states is as follows::
Example:
Thread.State ts = thrd.getState();
if(ts == Thread.State.RUNNABLE) // ...