Home > Java > javaTutorial > What are the five states of Java threads

What are the five states of Java threads

WBOY
Release: 2023-05-27 22:35:55
forward
5755 people have browsed it

1. Five states of threads

From the operating system level, any thread generally has five states, namely creation, ready, running, blocked, and terminated.

(1) New state (NEW)

When using the constructor method to create a new thread in the program, such as new Thread(), the thread is in the creation state, and it already has Corresponding memory space and other resources, but execution has not yet started.

(2) Ready state (READ)

Starting a thread can be achieved by calling the start() method of the newly created thread object. When the thread starts, the thread enters the ready state (runnable)

The thread has the running conditions, but because the CPU has not yet been allocated, it enters the thread queue and queues up to wait for CPU service. Once the system selects a thread object to be executed, the object transitions from the waiting state to the executing state. The actions selected by the system are called "CPU scheduling". When the thread obtains the CPU, it enters the running state and automatically executes its own run method.

(3) Running state (RUNNING)

The thread enters the running state when the thread in the ready state is called and occupies processor resources. At this time, the run() method of the thread object is automatically called.

(4) Blocked state (BLOCKED)

An executing thread will be blocked under certain special circumstances, such as when it is artificially suspended or when time-consuming input and output operations need to be performed. out of the CPU and temporarily suspends its own execution, entering a blocking state.

If you use sleep(), suspend(), wait() and other methods in the executable state, the thread will be blocked. When blocked, the thread cannot enter the queue. Only when the cause of the blocking is eliminated, the thread enters the ready state and returns to the ready queue to wait. At this time, after being selected by the CPU schedule, it will continue execution from the original stopped position. .

Remember: After the blocking is eliminated, it returns to the ready state, not the running state.

(5) Death state (TERMINATED)

When the thread calls stop(), destroy() or run() and completes execution, the thread will be in the terminal state. A thread in a dead state does not have the ability to continue running.

2. The 6 states of Java threads

The life cycle of a thread in Java is divided into 6 states. The Thread class has an instance property and an instance method specifically used to save and obtain the state of the thread. Among them, the instance attributes used to save the thread Thread instance state are:

// 以整数的形式保存线程的状态
private volatile int threadStatus = 0;
// 返回当前线程的状态,一个枚举类型值
public State getState() {
    return sun.misc.VM.toThreadState(threadStatus);
}
Copy after login

Thread.State is an internal enumeration class that defines 6 enumeration constants, representing the 6 states of Java threads, as follows :

public enum State {
    // 新建状态
    NEW,
    // 运行状态
    RUNNABLE,
    /**
     * 阻塞状态
     * Object.wait
     */
    BLOCKED,
    /**
     *  等待状态
     *  Object.wait
     *  Thread.join
     *  LockSupport.park
     */
    WAITING,
    /**
     *  限时等待状态
     *  Thread.sleep
     *  Object.wait
     *  Thread.join
     *  LockSupport.parkUntil
     *  LockSupport.parkNanos
     */
    TIMED_WAITING,
    // 终止状态
    TERMINATED;
}
Copy after login

There are 4 common states, they are: NEW (new) state, RUNNABLE (executable) state, TERMINATED (termination) state, TIMED_WAITING (time-limited waiting) state.

(1) NEW state

The Java source code explains the NEW state as follows: Thread thread instances that are successfully created but are not started by calling the start() method are in the NEW state.

Of course, once the start() method of the Thread thread instance is called, its state will change from the NEW state to the RUNNABLE state. This does not mean that the thread immediately obtains the CPU time slice and executes it immediately. A period of time is required in the middle. Internal operations of series operating systems.

(2) RUNNABLE state

After calling the start() method of the Thread instance, if the thread obtains the CPU time slice and starts execution in the next step, the JVM will asynchronously call the thread's run() method Execute its business code. So what did the JVM do before the run() method was called asynchronously? When the start() method of the Thread instance of a Java thread is called, the corresponding thread in the operating system does not enter the running state, but the ready state, and the Java thread does not have this ready state. What is the readiness state of threads in the operating system? The conversion relationship between the JVM's thread state and the operating system thread state behind it is simplified as follows:

What are the five states of Java threads

If an operating system thread is in the ready state, it means "everything is ready" "I am ready, I only owe the east wind", that is, the thread has met the execution conditions, but it cannot be executed yet. The thread in the ready state needs to wait for the system's scheduling. Once the ready state is selected by the system and obtains the CPU time slice, the thread begins to occupy the CPU and begins to execute the thread's code. At this time, the operating system state of the thread changes and enters the running state. .

When the running thread in the operating system uses up the CPU time slice, it will return to the ready state and wait for the next CPU scheduling. In this way, the operating system thread is repeatedly scheduled by the system between the ready state and the execution state. This situation will continue until the thread's code logic execution is completed or the thread terminates abnormally. At this time, the operating system state of the thread has changed again, entering the final state of the thread - TERMINATED state.

Ready state and running state are both thread states in the operating system. In the Java language, these two states are not subdivided, but merged into the same state - the RUNNABLE state. Therefore, in the Thread.State enumeration class, the ready state and running state of the thread are not defined, only the RUNNABLE state is defined. This is where the Java thread state differs from the thread state in the operating system.

When the Thread instance is in the NEW state, once the start() method is called, the thread will transition to the RUNNABLE state. Despite this, the thread's run() method may not be executed concurrently immediately. Concurrent execution needs to be started after the thread obtains the CPU time slice.

(3) TERMINATED state

When the thread in the RUNNABLE state finishes executing the run() method, it will enter the termination state TERMINATED. Of course, if a runtime exception occurs during the execution of the run() method and is not caught, the run() method will be terminated abnormally and the thread will also become TERMINATED.

(4) TIMED_WAITING state

The thread is in a special waiting state. To be precise, the thread is in a time-limited waiting state. The operations that can put a thread in a time-limited waiting state include the following:

  • Thread.sleep(int n): causes the current thread to enter a time-limited waiting state with a waiting time of n milliseconds.

  • Object.wait(): Preempt the monitor lock of the object with a time limit.

  • Thread.join(): Time-limited thread merging.

  • LockSupport.parkNanos(): Let the thread wait, the time is in nanoseconds.

  • LockSupport.parkUntil(): Let the thread wait, and the time can be set flexibly.

3. Java thread state transition

What are the five states of Java threads

The above is the detailed content of What are the five states of Java threads. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template