How to Temporarily Suspend a Thread in Java?
Threads in java are the lightweight sub-processes that can be created by the user. It is used to perform complicated tasks in the background without disturbing the main program. In order to suspend the thread temporarily by making it go through from running state to waiting for the state. The concept used in achieving the goal is the suspend() function.
Method: How the threads can be suspended temporarily
- Creating ‘MyThread Class‘ which is extending the ‘java.lang.Thread class‘. It has a run() function which contains some code to perform.
- In the main function, a ‘MyThread Class‘ object is created ‘thread’ which is named as ‘GFG’ by using the setName() function.
- Start the thread to perform its tasks by calling the start() function and it starts executing the code written in the run() function.
Sometimes there is an urgency to suspend these threads for some reasons. So here the program shows how the thread is suspended temporarily by using the suspend() function. The thread will go from running state to waiting state. This function makes a thread temporarily cease execution. The thread will remain in waiting for the state until we resume it. So, in this program the thread is kept suspended till the sleep time i.e. 5 seconds (taken in this program) is over, and then we resume it by using the resume() function.
Syntax: In order to get the ID number of the current thread is already created
Thread.currentThread( ).getId( ) ;
Methods Used:
- start(): This is a method to start the functioning of a thread.
- setName(): This is a method used to set the name of a thread that is created.
- sleep(time): This is a method used to sleep the thread for some milliseconds time.
- suspend(): This is a method used to suspend the thread. The thread will remain suspended and won’t perform its tasks until it is resumed.
- resume(): This is a method used to resume the suspended thread.
Example:
Java
import java.util.*;
class MyThread extends Thread {
public void run()
{
try {
System.out.println(
"Thread " + Thread.currentThread().getId()
+ " is running" );
}
catch (Exception e) {
System.out.println( "Exception is caught" );
}
}
}
public class GFG {
public static void main(String[] args) throws Exception
{
MyThread thread = new MyThread();
thread.setName( "GFG" );
thread.start();
Thread.sleep( 500 );
thread.suspend();
System.out.println(
"Thread going to sleep for 5 seconds" );
Thread.sleep( 5000 );
System.out.println( "Thread Resumed" );
thread.resume();
}
}
|
Output :
Thread 13 is running
Thread Suspended
Thread going to sleep for 5 seconds
Thread Resumed
Last Updated :
13 Jul, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...