Interview Questions

How thread can enter waiting, sleeping and blocked state and how can they go to runnable state ?

Java Interview Questions and Answers (part 4)


(Continued from previous question...)

33. How thread can enter waiting, sleeping and blocked state and how can they go to runnable state ?

This is very prominently asked question in interview which will test your knowledge about thread states. And it’s very important for developers to have in depth knowledge of this thread state transition. I will try to explain this thread state transition by framing few sub questions. I hope reading sub questions will be quite interesting.

> How can Thread go from running to waiting state ?
By calling wait() method thread go from running to waiting state. In waiting state it will wait for other threads to release object monitor/lock.

> How can Thread return from waiting to runnable state ?
Once notify() or notifyAll() method is called object monitor/lock becomes available and thread can again return to runnable state.

> How can Thread go from running to sleeping state ?
By calling sleep() method thread go from running to sleeping state. In sleeping state it will wait for sleep time to get over.

>How can Thread return from sleeping to runnable state ?
Once specified sleep time is up thread can again return to runnable state.

Suspend() method can be used to put thread in waiting state and resume() method is the only way which could put thread in runnable state.

Thread also may go from running to waiting state if it is waiting for some I/O operation to take place. Once input is available thread may return to running state.

>When threads are in running state, yield() method can make thread to go in Runnable state.

(Continued on next question...)

Other Interview Questions