Thread life cycle in java
In Java, the life cycle of a thread refers to the stages a thread goes through from its creation to its termination. The Java thread life cycle is represented by the following states:
- New: The thread is in this state when an instance of the
Threadclass is created but before the
start()method is called.
- Runnable: The thread is in this state after calling the
start()method. It is ready to run, but the scheduler has not selected it to be the running thread yet.
- Blocked: The thread is in this state when it is waiting for a monitor lock to enter a synchronized block/method or waiting for I/O operations to complete.
- Waiting: The thread is in this state when it is waiting indefinitely for another thread to perform a particular action.
- Timed Waiting: The thread is in this state when it is waiting for another thread to perform a particular action, but with a specified waiting time.
- Terminated: The thread is in this state when its
run()method completes or when the
stop()method is called.
Here’s an example that illustrates the Java thread life cycle:
In this example:
myThreadis in the New State after its creation.
- After calling
start(), it enters the Runnable State and becomes eligible for execution.
- Inside the
run()method, it is in the Runnable State as it is actively executing.
sleep(2000)call puts it into the Timed Waiting State for 2 seconds.
- The main thread (
main()method) sleeps for a while, putting the main thread into the Timed Waiting State.
join()method is called, putting the main thread into the Blocked State until
myThreadcompletes, it enters the Terminated State.
When you run this program, you’ll see output indicating the different states the threads are in during their life cycle. Keep in mind that the exact order of states might vary due to the nature of thread scheduling.