Let's start with a thread state conversion diagram:
Big Idler Chai Maomau
Links: https://www.zhihu.com/question/27654579/answer/252912242
Source: Know
Copyright belongs to the author. Commercial reprint please contact the author for authorization, non-commercial reprint please specify the source.
The state of the threads in Java is divided into 6 types altogether:
Initial state: NEW
When you create a thread object, but you have not yet called start (), the thread is in the initial state.
operating state: RUNNABLE
In Java, the run state includes the ready state and the run state.
- Ready state
- The thread in this state has been given all the resources required to execute, as long as the CPU is assigned execution rights to run.
- All ready-to-state threads are stored in the ready queue.
- Operating State
- Gets the CPU execution right that is executing the thread.
- Because one CPU can only execute one thread at a time, each CPU has only one running thread at a time.
blocking states
- When an executing thread requests a resource to fail, it enters a blocking state.
- In Java, the blocking states refer to the State entered when the request lock fails.
- The thread that holds all the blocked states by a blocking queue.
- A blocked thread constantly requests resources, and once the request succeeds, it enters the ready queue and waits for execution.
PS: Locks, IO, sockets and other resources.
Waiting State
- When a wait, join, park function is called in the current thread, the current thread enters the waiting state.
- There is also a thread waiting for the queue to hold all waiting states.
- A thread in a waiting state indicates that it needs to wait for instructions from another thread to continue running.
- The thread that enters the waiting state releases the CPU execution and frees the resource (for example, lock)
Timeout Wait State
- When a running thread calls sleep (time), wait, join, Parknanos, Parkuntil, it enters that state;
- It is the same as the waiting state, not because the request is not a resource, but the active entry, and the need to wake up other threads;
- After entering this state, the CPU execution and possession resources are freed.
- difference from waiting state: automatically enters the blocking queue after the time-out period and starts the competition lock.
Termination State
The state after the thread execution has ended.
Conversion status between threads