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( ) ;
- 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.
Thread 13 is running Thread Suspended Thread going to sleep for 5 seconds Thread Resumed
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready.