2021-03-17

1. The life cycle of a thread-six states

This is defined in the enumeration class of java.lang.Thread.State:

    public enum State {
    
    
        NEW,
        RUNNABLE,
        BLOCKED,
        WAITING,
        TIMED_WAITING,
        TERMINATED;
    }

First of all, it does not distinguish between ready and running status, because for Java objects, they can only be marked as runnable. As for when to run, it is not controlled by the JVM, but scheduled by the OS, and the time is very short. The state of Java objects cannot be distinguished. We can only imagine and understand artificially.

Secondly, according to the definition of Thread.State, the blocking state is divided into three types: BLOCKED, WAITING, and TIMED_WAITING.

  • BLOCKED: Refers to several threads competing with each other. When one thread occupies the lock object, the other threads can only wait for the lock. Only the thread that acquired the lock object has the opportunity to execute.
  • TIMED_WAITING: When the current thread is executing sleep or join of the Thread class, wait of the Object class, and the park method of the LockSupport class, and when these methods are called, the time is set, then the current thread will enter TIMED_WAITING until the time is up, or Was interrupted.
  • WAITING: When the current thread encounters the wait of the Object class, the join of the Thread class, and the park method of the LockSupport class during the execution of the current thread, and when these methods are called without a specified time, the current thread will enter the WAITING state until it is awakened.
    • Entering the WAITING state through the wait of the Object class must be awakened by the notify/notifyAll of the Object;
    • To enter the WAITING state through Condition's await, Conditon's signal method must be awakened;
    • To enter the WAITING state through the park method of the LockSupport class, the unpark method of the LockSupport class must be awakened
    • Enter the WAITING state through the join of the Thread class, and the current thread can be restored only when the thread object calling the join method ends;

Note: When restoring to the Runnable state from WAITING or TIMED_WAITING, if it is found that the current thread does not get the monitor lock, it will immediately switch to the BLOCKED state.

Insert picture description here

Guess you like

Origin blog.csdn.net/qq_37698495/article/details/114952375