Last Updated:

The lifecycle of the Java stream. Thread State in Java

In the last lesson we learned how to work with Java Thread and got acquainted with the Runnable interface.

Java Stream State

The diagram below shows the different flow states in Java. Note that we can create a thread in Java and run it, but how the state of the thread changes from Runnable to Running and Blocked depends on the implementation of the system Thread scheduler and java does not have complete control over this process. Figure 1 shows this process:

Stream States in Java

Figure 1 — Stream States in Java

1. Flow status: New

When we create a new class object using the , the flow is in the . In this state, the thread is not yet running.ThreadnewNew

2. Stream State: Runnable

When we call the method of the created object, its state changes to and the flow control is passed to the Thread scheduler. Whether to run this thread instantly or save it to a healthy thread pool before running it depends on how the OS is implemented in the thread scheduler.start()ThreadRunnable

3. Stream State: Running

When the thread starts, its state changes to Running. The thread scheduler selects a single thread from its shared thread pool and changes its state to Running. Immediately after that, the processor starts executing this thread. At run time, the state of the thread can also change to Runnable, Dead, or Blocked.

4. Stream state: Blocked or Waiting

A thread can wait for another thread to complete its work, such as waiting for resources to be released or for I/O to be released. In this case, its state changes to Waiting. After a thread is finished waiting, its state changes to Runnable and it is returned to the shared thread pool.

5. Stream Status: Dead

After the thread completes execution, its state changes to Dead, that is, it has worked out its own and is no longer needed.

That's all you need to know about thread states in Java and how the Thread scheduler works.