The premise is introduced

This chapter mainly introduces the conversion mechanism of the relevant thread declaration cycle and the circulation relationship of the declaration cycle as well as the implementation and basic principles of the relevant AQS, with the introduction of the translation of the relevant official documents in Chinese and English.

Thread state flow and life cycle

When a thread is created and started, it is neither in the execution state as soon as it is started nor always in the execution state. In its life cycle, a thread passes through six states: New, Runnable, Blocked, Wait, Time_wait, and Terminate. Especially when a thread is started, it cannot always “hog” the CPU to run alone, so the CPU needs to switch between multiple threads, so the thread state will switch between running and blocking many times.

The image below is taken from the official website:

Six states of the life cycle

The whole process of a thing from the moment of its birth to its final death. In the course of its long life cycle, things always go through different states (infant state/adolescent state/middle age state/old age state…). Thread also has a life cycle, but also there are different states, states between the conversion.

The State of Thread objects is stored in the inner class of Thread:

 public enum State {
        /** * Thread state for a thread which has not yet started. */
        NEW,

        /** * Thread state for a runnable thread. A thread in the runnable * state is executing in the Java virtual machine but it may * be waiting for other resources from the operating system * such as processor. */
        RUNNABLE,

        /**
         * Thread state for a thread blocked waiting for a monitor lock.
         * A thread in the blocked state is waiting for a monitor lock
         * to enter a synchronized block/method or
         * reenter a synchronized block/method after calling
         * {@link Object#wait() Object.wait}.
         */
        BLOCKED,

        /**
         * Thread state for a waiting thread.
         * A thread is in the waiting state due to calling one of the
         * following methods:
         * <ul>
         *   <li>{@link Object#wait() Object.wait} with no timeout</li>
         *   <li>{@link #join() Thread.join} with no timeout</li>
         *   <li>{@link LockSupport#park() LockSupport.park}</li>
         * </ul>
         *
         * <p>A thread in the waiting state is waiting for another thread to
         * perform a particular action.
         *
         * For example, a thread that has called <tt>Object.wait()</tt>
         * on an object is waiting for another thread to call
         * <tt>Object.notify()</tt> or <tt>Object.notifyAll()</tt> on
         * that object. A thread that has called <tt>Thread.join()</tt>
         * is waiting for a specified thread to terminate.
         */
        WAITING,

        /**
         * Thread state for a waiting thread with a specified waiting time.
         * A thread is in the timed waiting state due to calling one of
         * the following methods with a specified positive waiting time:
         * <ul>
         *   <li>{@link #sleep Thread.sleep}</li>
         *   <li>{@link Object#wait(long) Object.wait} with timeout</li>
         *   <li>{@link #join(long) Thread.join} with timeout</li>
         *   <li>{@link LockSupport#parkNanos LockSupport.parkNanos}</li>
         *   <li>{@link LockSupport#parkUntil LockSupport.parkUntil}</li>
         * </ul>
         */
        TIMED_WAITING,

        /** * Thread state for a terminated thread. * The thread has completed execution. */
        TERMINATED;
    }
Copy the code

Note that the Thread.State class is actually an enumeration class. Because thread object states are fixed and there are only six, enumerations are used to indicate yes.


New Thread
  • When an instance (object) of the Thread class is created, the Thread enters the new state (not started).

  • Use new to create a thread object that simply allocates memory in the heap before calling the start method. In the new state, the thread is not started at all, only a thread object exists. Thread t = new Thread();

  • Now t is in the new state and when the thread object in the new state calls the start method, it goes from the new state to the runnable state. Thread object’s start method can only be called once, otherwise an error: IllegalThreadStateException.

For example,
Thread  t1=new Thread();
Copy the code

Runnable

There are two sub-states, ready and running. Indicates the ready state and running state respectively.

The ready state

After calling the start method, the thread object is waiting for the JVM to schedule (the thread is not running at this time), and the thread is waiting for the CPU to allocate resources first. In other words, the thread has been started and is waiting for the CPU to allocate time slice. This means that the thread is queuing in the ready queue for CPU resources.

Running state

Thread objects get JVM scheduling, allowing multiple threads to run in parallel if there are multiple cpus

  • Is translated into Terminated state, such as calling the stop() method;

  • The state is converted to Blocked, such as when sleep is called, and the wait method is added to waitSet;

  • The vm is converted to the Blocked state. For example, when I/O blocking is performed, for example, when a database is queried, the VM is Blocked.

  • Converted to Blocked, such as when a lock is released and added to the blocking queue for that lock;

  • When the time slice of the thread runs out, the CPU schedules the thread again and enters the Runnable state.

  • The thread actively invokes the yield method to release CPU resources and enter the Runnable state

For example,
t1.start();
Copy the code
It also belongs to the Runnable state, but not the general state. It belongs to the logical state mechanism

When a ready thread is scheduled to acquire CPU resources, it enters the run state. The run method defines the actions and functions of the thread, and the thread will continue to run until the end unless the thread automatically abandons CPU resources or a higher priority thread enters.

Note:

Threads in Runnable state cannot enter the Blocked or Terminated state directly. Only threads in the Running state — in other words, only threads that are assigned CPU execution rights — are eligible to enter the Blocked and Terminated states. Threads in the Runnable state can either be switched to Running or Terminated unexpectedly.

They are blocked.

When a running thread, for some reason, abandons the CPU and temporarily stops running, it enters a blocking state. The JVM does not allocate CPU to the thread until it re-enters the ready state and has a chance to return to the running state. The blocked state can only enter the ready state first, but cannot enter the running state directly.

Two cases of blocking:
  1. When thread A tries to acquire the lock while running, thread B acquires the lock. At this point, the JVM stores the current THREAD A into the lock pool of the object, and the thread A enters the blocking state.
  2. A thread is blocked when it makes an IO request while it is running.

A running thread enters a blocked state when for some reason it relinquish the CPU and pauses its execution.

  • Is translated into Terminated state, such as a call to the stop() method or an unexpected Crash of the JVM;

  • The state is changed to Runnable and the blocking time is over, such as after reading data from the database;

  • The Runnable state has been set to sleep for the specified time.

  • A thread in wait is awakened by notify/notifyAll calls from another thread and enters the Runnable state.

  • The thread acquires the desired lock resource and enters the Runnable state.

  • A thread is interrupted in a blocking state, such as when another thread calls the interrupt method and enters the Runnable state.

Waiting state

The wait state can only be awakened by other threads.

The no-argument wait method used in this case,

  1. The wait() method is called while the thread is running, and the JVM stores the current thread in the object wait pool.
Timed wait state

(Use wait or sleep with arguments)

  1. When a thread is running, the WAIT (long time) method is called, and the JVM stores the current thread in the object wait pool.
  2. : The current thread executed the sleep(long time) method.
Terminated state (terminated)

Usually referred to as a dead state, the thread terminates.

  1. Exit after executing the run method normally (normal death).
  2. Exit when an exception occurs (the program breaks after an exception occurs)(accidental death).
  3. The JVM terminates abnormally and all thread lifetimes are terminated.

Threads when you stop, can’t again to restart starts, otherwise an error (IllegalThreadStateException).

The threading method is not recommended

Obsolete methods in the Thread class (deprecated due to thread-safety concerns):

  • Void suspend() : suspends the current thread
  • Void Resume () : restores the current thread
  • Void stop() : terminates the thread

To give you a Chinese explanation of the state flow diagram in combination with the official website: