Introduction to life cycle of a simple thread in Java :-
Life cycle of a thread in Java has many important states. These states defines the functionality and working of Java threads. There are normally five states through which a thread can go from birth to death. The states are as follows :-
Life cycle diagram of a thread in Java :-
Life cycle of a thread in Java has many important states. These states defines the functionality and working of Java threads. There are normally five states through which a thread can go from birth to death. The states are as follows :-
- New :- Whenever we instantiate an object of class Thread, we create a new thread which goes to new state. It is the state which signifies that a new thread is created but its not ready to run.
- Runnable :- After creation of thread when we call Thread's start method, it changes state of a thread from new to runnable. This transition does not make thread to run but it makes a thread eligible to run. After reaching this state thread gets a call from Java Thread Scheduler to run. Thread Scheduler selects one of the runnable thread after processor becomes available to it.
- Blocked :- Generally , threads can move to blocked state due to various reasons, some of the reasons are waiting for I/O operation , waiting for any network connections etc. Usually a thread gets back to its runnable state when it finishes its operation which has blocked it. A blocked thread can't be run by thread scheduler , it has to get back to runnable state to run.
- Waiting :- A thread can enter to a waiting state by calling wait method over it. It can go to runnable state whenever another thread calls notify or notifyAll method to send notification to it for getting back to runnable state.
- Terminate :- A thread terminates when run method completely executes itself. Once a thread terminates it never gets back to its runnable state.
Life cycle diagram of a thread in Java :-