Suspend Resume Thread Java

Suspend Resume Thread Java

Introduction to Suspend Resume Thread

When the sleep() method time is over, the thread becomes implicitly active. sleep() method is preferable when the inactive time is known earlier. Sometimes, the inactive time or blocked time may not be known to the programmer earlier; to come to the task here comes suspend() method. The suspended thread will be in blocked state until resume() method is called on it. These methods are deprecated, as when not used with precautions, the thread locks, if held, are kept in inconsistent state or may lead to deadlocks.

Note: You must have noticed, in the earlier sleep() method, that the thread in blocked state retains all its state. That is, attribute values remains unchanged by the time it comes into runnable state.

Suspend Resume Thread: Program explaining the usage of suspend() and resume() methods


Suspend Resume Thread Java
Output screen on Suspend Resume Thread Java

Observe the screenshot, when no thread is suspended both threads are under execution. When First thread goes into suspended state, the Second thread goes into action. Similarly, when the Second goes to suspended state, the First is executed.

Note: When you compile this program, you will get deprecated warning. But the program works happily.

Note: Depending on the microprocessor speed and OS architecture, you may get a different output or different outputs at different times of execution. But do not worry.

6 thoughts on “Suspend Resume Thread Java

  1. Ramakrishna

    class Sus_Resume extends Thread
    {
    public void run()
    {
    for(int i=0;i<100;i++)
    {
    System.out.println("child theread:"+i);
    }
    }
    public static void main(String[] args)
    {
    Sus_Resume s=new Sus_resume();
    s.start();

    for(int j=0;j<100;j++)
    {
    System.out.println("main thread:"+j);

    if(j==60)
    {
    System.out.println("child thread suspend:");
    s.suspend();
    }

    if(j==80)
    {
    System.out.println("child thread resume:");
    s.resume();
    }

    }
    }

    }

    on above program both child and main threads are going to stop at 60, why it is not going to resume. and why main thread going to execution stop

  2. Abhinav Joshi

    Sir,
    I didn’t get this program. When the execution came to
    “srd1.start();”
    why “srd2.start();” started immediately.

    How the execution jumped from srd1.start() to srd2.start().

Leave a Reply

Your email address will not be published. Required fields are marked *