The life cycle of a Thread

The Thread class in Java also has an internal enumeration class, STATE, that represents the STATE of the Thread from beginning to end,

NEW

Refers to a newly created thread that has not yet started execution

RUNNABLE

Being in this state means that the current thread is executing or waiting for execution, or maybe even waiting for IO,

This raises the question, if a thread is waiting for IO, shouldn’t it be blocked?

In the JVM, a thread’s BLOCKED state is used to represent another special case, and when a thread calls IO, it makes an open Linux system call,

At this point, the CPU finds that the thread needs to perform I/O operations and switches to another thread. However, the current Java thread is still in the RUNNABLE state even though it is not being executed by the system.

When the IO event is completed, an interrupt signal will be sent. The CPU senses the arrival of the interrupt signal and will resume the execution of the thread.

The thread is still in the RUNNABLE state. There is an I/O block, but it is operating system level blocking, independent of the thread in the JVM, so the thread’s state remains unchanged from the beginning of the I/O event to the end

BLOCKED

This state refers to a thread waiting for a Monitor lock, which is also known as synchronized. In other words, the thread is BLOCKED while waiting for a lock, which is not associated with the blocking of the operating system

WAITING

A thread that calls several methods will be in this state

Object.wait, Thread.join, locksupport. park

TIMED_WAITING

A thread that calls several methods will be in this state

Thread.sleep, Object.wait, Thread.join, locksupport. parkNanos, locksupport. parkUntil

WAITING and TIMED_WAITING are two state-dependent trigger methods that involve collaborative synchronization between Java multithreads, more on this later

TERMINATED

The thread becomes this state when execution is complete or interrupted