Thread suspend() method in Java

In this tutorial, we will talk about a special method of the Thread class. In order to understand the thread suspend() method in Java, we need to first understand the life cycle of a thread and how the suspend method can be used to a programmer’s benefit.

What is a thread?

A thread is a lightweight process that forms the basic unit of the CPU execution process. Java allows us to use multi-threading i.e running multiple threads at the same time.

Life Cycle of a Thread

A thread from the moment it is created until it dies may have 5 different states. It can switch between states by using certain methods such as start, run, sleep, suspend, resume, notify, yield, etc.

The life cycle looks like this :

Suspend() Method in Thread class in Java

Suspend() Method in Thread class in Java

Due to the multi-threading concept, we may need to block one particular thread while some other thread is executing. As we have seen in the life cycle diagram, there are several inbuilt methods provided to us by the thread class to change the state of a thread. One of them is the suspend() method. It is used to change the thread from Running state to Suspended/Blocked state.

Thread suspend() method in Java

It is a public, final method hence it is always accessible and cannot be changed. Suspend() has a void return type.

A code snippet is provided below to explain the working of the suspend() function :

 

class ThreadExample extends Thread{
    public void run(){
        int n=5;
        for (int i=1;i<=5;i++){
            System.out.println(i);
        }
        try{
            sleep(500);
            System.out.println(Thread.currentThread().getName());
        }
        catch(InterruptedException e){
            System.out.println("Exception occured");
        }
        finally {
            System.out.println("End of Example!");
        }
    }
}


class Main2 {
    public static void main(String[] args) {
        ThreadExample t1 = new ThreadExample();
        ThreadExample t2 = new ThreadExample();
        ThreadExample t3 = new ThreadExample();

        t1.start();
        t2.start();

        t3.start();

        t2.suspend();

        t1.resume();

        t3.suspend();

        t2.resume();

        t3.resume();



    }
}


 

Output :

 

1
2
3
4
5
1
2
3
4
5
1
2
3
4
5
Thread-0
End of Example!
Thread-2
End of Example!
Thread-1
End of Example!

 

We see here that the thread 2 has finished execution before thread 1. This is because of the order of the call stack and can vary according to the OS used.

I hope this was insightful!

Also read: Overriding toString() method in Java

Leave a Reply

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