Suspending, Resuming and Stopping Threads in Java

The functions of Suspend, Resume and Stop a thread is performed using Boolean-type flags in a multithreading program. These flags are used to store the current status of the thread.

1. If the suspend flag is set to true then run() will suspend the execution of the currently running thread.

2. If the resume flag is set to true then run() will resume the execution of the suspended thread.

3. If the stop flag is set to true then a thread will get terminated.

Program:

class temp implements Runnable
{
Thread Th;
boolean suspend_flag, stop_flag;
temp(String tN)
{
Th=new Thread(this, tN);
suspend_flag=false;
stop_flag=false;
Th.start();
}
public void run()
{
try
{
int j=1;
while(++j<20)
{
synchronized(this)
{
while(suspend_flag)
{ wait();}
if(stop_flag)
{ break;}
}
}
}
catch(InterruptedException IE)
{
System.out.println("Thread Interrupted");
}
}
synchronized void my_suspend()
{
suspend_flag=true;
}
synchronized void my_resume()
{
suspend_flag=false;
notify();
}
synchronized void my_stop()
{
suspend_flag=false;
stop_flag=true;
notify();
}
}
public class SRS
{
public static void main(String args[])
{
try
{
temp t1=new temp("SRS");
System.out.println("Thread SRS is Created and Started");
Thread.sleep(2000);
t1.my_suspend();
System.out.println("Thread SRS is Suspended");
Thread.sleep(2000);
t1.my_resume();
System.out.println("Thread SRS is Resumed");
Thread.sleep(2000);
t1.my_suspend();
System.out.println("Thread SRS is Suspended");
Thread.sleep(2000);
t1.my_resume();
System.out.println("Thread SRS is Resumed");
Thread.sleep(2000);
t1.my_stop();
System.out.println("Thread SRS is Stopped");
}
catch(InterruptedException IE)
{
System.out.println("Generated interrupted exception");
}
}
}

Output:
Suspending, Resuming and Stopping Threads in Java

Thead Priority:

In Java, each thread is assigned a priority which affects the order in which it is scheduled for running. The threads are of the same priority by the Java Scheduler and therefore they share the processor on a First-Come-First-Serve basis.
Java permits us to set the priority of a thread using the setPriority() as follows:

Thread-Name.setPriority(intNumber);

Where intNumber is an integer value to which the thread’s priority is set. The Thread class defines several priority constants:

MIN_PRIORITY = 1
NORM_PRIORITY = 5
MAX_PRIORITY = 10