Thread life cycle
Thread
goes through various stages in its lifecycle.
for example in laymen terminologies we are creating the thread, starting the thread,
running the threads, waiting the thread, terminating the thread.
A thread can be in one of the five states
1) New State
2) Runnable
State
3) Running
State
4) Non-Runnable
State
5) Terminated
1) New State:
A new
thread begins its life cycle in the new state, in this state a thread has been
created, but it has not yet started.
A thread
is started by calling it’s start() method.
Note: start()
method is executing its referenced object run() method.
run()
method available inside thread class and runnable interface.
If we
want to create a new thread we should override run() method by extending Thread
class/implementing Runnable Interface.
2) Runnable State:
This
state is also called ready to run state, also called queue.
A thread
starts life in the ready to run state by calling start() method and wait for its
turn.
The
Thread scheduler decides which thread runs and for how long.
Note:
thread scheduler in Java is part of JVM that decides which thread should run
and which thread should wait there are number of factor or criteria which are
used to select a thread.
The
thread scheduler always chooses a thread to run only if it is in the runnable
state.
3) Running State:
The Running
state doesn’t exist in reality but its consider as a part of runnable state.
In
runnable state the control transfer to the thread scheduler and thread
scheduler picks one of the threads from the Runnable thread pool and change its
state to Running.
If a
thread is in running state, it means that the thread is currently executing.
4) Non-Runnable State:
When a
thread is in the Blocked state it is not eligible to run. Although the thread
is considered to be alive.
A Runnable
thread can move to the Blocked state if a thread wants to perform some
operation but can’t complete immediately so it must temporarily wait until that
task completes.
After
the Blocked state, the thread moves to the Runnable state and waiting for the
CPU cycle.
5) Terminated:
It is the
state of a dead thread, it’s in the terminated state. When it has either
finished execution or was terminated abnormally.
A thread
after exit from the run() method will be in terminated state, or we can stop
the thread forcefully using stop() method.
Inter Thread Communication
The
wait() method is used for interthread communication.
The
wait() method is defined in Object class which is the super most class in Java.
In Java
synchronized methods and blocks allow only one thread to acquire the lock on a
resource at a time.
So wait()
method called by a thread, than it gives up the lock on that resource and goes
to sleep until some other thread enters
the same monitor and calls notify() or notifyAll().
It is a
final method, so we can’t override it.
Example Program:
No comments:
Post a Comment