Thread life cycle: – During the life time of a thread, there are many states it can enter. Thread include –
- Newborn state
- Runnable state
- Running state
- Blocked state
- Dead state
Newborn state: – When we create a thread object, the thread is born and is said to be in new born state. The thread is not yet scheduled for running. At this state, we can do only one of the following things with it.
- Schedule it for running using start() method.
- Kill it using stop() method
If scheduled, it moves to the runnable state. If we attempt to use any other method at this stage, an exception will be thrown.
Runnable state: – The runnable state means that the thread is ready for execution and it waiting for the availability of the processor. That is the thread has joined the queue of thread that are waiting for execution. If all threads have equal priority, then they are given time slates for execution in round robin fashion. The thread that relinquishes control joins the queue at the end and again waits for its run. This process of assigning time to thread is known as time slicing. However, if we want a thread to relinquish control to another thread to equal priority before its turn to comes, we can do so by using the yield method.
Running state: – A running means that the process has given its time to the thread for its execution. The thread runs until a relinquishes control on its own or it is preempted by a higher priority thread. A running thread may relinquish its control in one of the following situations –
- It has been suspended using suspend() method. A suspend thread can be revived by using the resume() method. This approach is useful when we want to suspend thread for some time to certain session, but do not want to kill it.
- It has been made up to sleep. We can put a thread to sleep for a specified time period using the method sleep(time) where time is in millisecond. This means that the thread is out of the queue during this time period 1000=1 second. The thread reenters the runnable state as soon as this time period is elapsed.
- It has been told to wait until some event occurs. This is done using the wait() method. The thread can be rescheduled to run again using the notify() method.
Blocked state: – A thread is said to be blocked when it is prevented from entering into the runnable state and subsequently the running state. This happens when the thread is suspended, sleeping, or waiting in order to satisfy certain requirements. A blocked thread considered not runnable but not deal and there for fully qualified to run again.
Deal state: – Every thread has a life cycle. A running thread ends its life when it has completed executing its run() method. It is natural death. However, we can kill it by sending the stope message to it at any state thus causing the premature death to it. A thread can be killed as shown as it is born, or while it running, or even it is in not robbable condition.