Sunday, June 22, 2014

Thread life cycle in java

Thread life cycle in java | life cycle of thread in java | java thread life cycle

When we look at the thread life cycle in java it will show, how to create a thread, how to stop a thread, how to java thread sleep and some other stages of thread life cycle in java.
The following figure illustrates the various states that a java thread can be in any point during its life cycle. It also illustrates which method calls cause a transition to other state in the thread life cycle of java. The various states in the thread life cycle in java are: -
  • New
  • Runnable
  • Not Runnable
  • Dead  or Terminate

New Thread: -When we createan instance of the Thread class, the thread enters the new thread state in thread life cycle. The following statement creates a new thread: -
ThreadmyThread = new Thread ();
By this syntax a new thread is created. This new thread is an empty object of the thread class which have no system resources allocated. We have to invoke the start() method to start the thread. The following statement start a thread: -
myThread.start();
Note that when the thread is in the new state, no other method except the start() method can be called, otherwise it throws IllegalThreadStateException.

Runnable Thread: -When we invoke the start() method of a thread, the thread enters the runnable state in thread life cycle. This start() method allocates the system resources to the thread and call its run() method and schedules the thread.
When we talk about single processor system, it is impossible to run all runnable threads in the same time. So the java runtime system must implement a scheduling scheme that shares the processors between all the runnable threads. The thread is in running state when the thread scheduler selects it to be the currently executing process.

Not Runnable: -A thread enters the Not Runnable state when one of the following event occurs in thread life cycle:
  • Invoke java threadsleep() method
  • Invoke java threadwait() method
  • Being blocked
Dead Thread: -A thread can either dead or alive. It can die in two ways: either form natural causes, or by being killed.
A thread die naturally when the loop in the run() method is complete. And we can also kill a thread at any time by calling stop() method. Also note that we cannot restart a dead thread.

No comments:

Post a Comment