Friends, don’t be silly to distinguish between the thread life cycle and the thread pool life cycle! ! !

Article Directory



Preface

The bloggers have been wandering in the Niuke Mianjing area all the year round, summarizing the high-frequency exam questions from big companies such as Byte, Ali, Baidu, Tencent, Meituan, etc., and will gradually share them with everyone afterwards. I look forward to your attention and praise!

Insert picture description here



Thread life cycle

Proof of source code


调用线程的getState方法:Thread.currentThread().getState();

    public State getState() {
        // get current thread state
        return sun.misc.VM.toThreadState(threadStatus);
    }
    
    public static State toThreadState(int var0) {
        if ((var0 & 4) != 0) {
            return State.RUNNABLE;
        } else if ((var0 & 1024) != 0) {
            return State.BLOCKED;
        } else if ((var0 & 16) != 0) {
            return State.WAITING;
        } else if ((var0 & 32) != 0) {
            return State.TIMED_WAITING;
        } else if ((var0 & 2) != 0) {
            return State.TERMINATED;
        } else {
            return (var0 & 1) == 0 ? State.NEW : State.RUNNABLE;
        }
    }

It can be seen that State is an enumeration class

    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;
    }
  • Initial (NEW): A thread object is newly created, but the start() method has not been called yet.
  • RUNNABLE: The two states of ready (ready) and running (running) are collectively called "running" in Java threads.
    After the thread object is created, other threads (such as the main thread) call the object's start() method. Threads in this state are in the runnable thread pool, waiting to be selected by thread scheduling to obtain the right to use the CPU, and are in the ready state (ready) at this time. A thread in the ready state becomes a running state after obtaining a CPU time slice.
  • Blocked (BLOCKED): the thread fails to acquire the lock and enters the blocked state
  • Waiting (WAITING): The thread entering this state needs to wait for other threads to make some specific actions (notification or interrupt).
Call Object.wait (), Thread.join(), LockSupport.park to enter the waiting state
  • Timeout waiting (TIMED_WAITING): The thread state of a waiting thread with a specified waiting time. This state is different from WAITING, and it can return by itself after a specified time.
Call Thread.sleep, Object.wait (long timeout), Thread.join (long millis), etc. to enter the supermarket waiting state
  • Termination (TERMINATED): Indicates that the thread has been executed.



Thread pool life cycle

Proof of source code

Insert picture description here
    private static final int RUNNING    = -1 << COUNT_BITS;
    private static final int SHUTDOWN   =  0 << COUNT_BITS;
    private static final int STOP       =  1 << COUNT_BITS;
    private static final int TIDYING    =  2 << COUNT_BITS;
    private static final int TERMINATED =  3 << COUNT_BITS;

1. RUNNING

  1. State description : When the thread pool is in the RUNNING state, it can receive new tasks and process the added tasks.
  2. State switching : The initialization state of the thread pool is RUNNING. In other words, once the thread pool is created, it is in the RUNNING state, and the number of tasks in the thread pool is 0!
private final AtomicInteger ctl = new AtomicInteger(ctlOf(RUNNING, 0));

2. ShutDown

State description : When the thread pool is in the SHUTDOWN state, it does not receive new tasks, but can process the added tasks.

State switching : When the shutdown() of the thread pool is called, the thread pool is changed from RUNNING -> SHUTDOWN.

3. STOP

State description : When the thread pool is in the STOP state, it does not receive new tasks, does not process the added tasks, and interrupts the tasks being processed.

State switching : When the shutdownNow() of the thread pool is called, the thread pool is changed from (RUNNING or SHUTDOWN) -> STOP.

4. tidying

State description : When all tasks have been terminated, the thread pool will change to TIDYING state. When the thread pool becomes TIDYING, the hook function terminated() will be executed. terminated() is empty in the ThreadPoolExecutor class. If the user wants to perform the corresponding processing when the thread pool becomes TIDYING; it can be achieved by overloading the terminated() function.

State switching : When the thread pool is in the SHUTDOWN state, the blocking queue is empty and the tasks executed in the thread pool are also empty, it will be SHUTDOWN -> TIDYING.

When the thread pool is in the STOP state, when the tasks executed in the thread pool are empty, it will be STOP -> TIDYING.

5. TERMINATED (terminated)

State description : The thread pool is completely terminated, and it becomes the TERMINATED state.

State switching : When the thread pool is in the TIDYING state, after the execution of terminated(), it will be TIDYING -> TERMINATED.



CSDN exclusive benefits are coming! ! !


Recently, CSDN has an exclusive event, which is the following "Java Full Stack Knowledge Graph". The route planning is very detailed, and the size is that 870mm x 560mmfriends can follow the above process for systematic learning. Don’t be like me. Bring yourself to find a book and study randomly, systematic and regular study, its foundation is the most solid, in our field, "The foundation is not strong, the ground is shaking" is especially obvious.

Finally, if you are interested, you can buy it as appropriate to pave the way for your future! ! !


Insert picture description here



Concluding remarks

I am a master of CRUD sketching , and I will continue to update blog posts that are beneficial to everyone in the future. I look forward to your attention! ! !

It’s not easy to create. If this blog post is helpful to you, I hope you guys canLike and follow me, Thanks for your support, see you next time~~~

Share outline

Dachang Interview Questions Column


Java From Entry to Grave Learning Route Catalog Index


Open Source Crawler Example Tutorial Catalog Index

For more exciting content to share, please click Hello World (●'◡'●)


Insert picture description here