Multi-threaded programming [high] five concurrent threads of the life cycle

Program ape Society of GitHub, welcome Star
https://github.com/ITfqyd/cxyxs
This article has been recorded to github, to form the corresponding topics.

Foreword

Heard read previous articles, we already have a general understanding of multi-threading. Everything in the world is orderly, people have a life cycle, early childhood -> Youth -> Youth, of course, the thread without exception. Follow the president take a look at the threads in illness and death, to go from.

1. By looking at the source code to understand the life cycle of the thread

First, the first knock Thread, View source class, to see all classes by the method of Alt + 7 (idea).
Here Insert Picture Description
This class we can find a State of enumeration class.

 /**
     * A thread state.  A thread can be in one of the following states:
     * <ul>
     * <li>{@link #NEW}<br>
     *     A thread that has not yet started is in this state.
     *     </li>
     * <li>{@link #RUNNABLE}<br>
     *     A thread executing in the Java virtual machine is in this state.
     *     </li>
     * <li>{@link #BLOCKED}<br>
     *     A thread that is blocked waiting for a monitor lock
     *     is in this state.
     *     </li>
     * <li>{@link #WAITING}<br>
     *     A thread that is waiting indefinitely for another thread to
     *     perform a particular action is in this state.
     *     </li>
     * <li>{@link #TIMED_WAITING}<br>
     *     A thread that is waiting for another thread to perform an action
     *     for up to a specified waiting time is in this state.
     *     </li>
     * <li>{@link #TERMINATED}<br>
     *     A thread that has exited is in this state.
     *     </li>
     * </ul>
     *
     * <p>
     * A thread can be in only one state at a given point in time.
     * These states are virtual machine states which do not reflect
     * any operating system thread states.
     *
     * @since   1.5
     * @see #getState
     */
    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;
    }

    /**
     * Returns the state of this thread.
     * This method is designed for use in monitoring of the system state,
     * not for synchronization control.
     *
     * @return this thread's state.
     * @since 1.5
     */
    public State getState() {
        // get current thread state
        return sun.misc.VM.toThreadState(threadStatus);
    }

getState method to get the status of the current thread.
Through this enumeration class, we can see that the thread of the life cycle of six species

  • NEW (New)
  • RUNNABLE (ready)
  • BLOCKED (blocking)
  • WAITING (waiting)
  • TIMED_WAITING (limit waiting)
  • TERMINATED (death or complete)
    Here Insert Picture Description

2. Example 6 kinds of thread appreciated cycle state.

NEW (New)

Just create a thread, not running, it is the new state of the thread.

public class New {
    public static void main(String[] args) {
        Thread t = new Thread();
        System.out.println(t.getState());
    }
}

Here Insert Picture Description

RUNNABLE (ready)

After a thread start method is called, he said he has been running the jvm, the cpu resources have not yet been scheduled. Ready to call it.

package com.cxyxs.thread.five;

/**
 * Description:转发请注明来源  程序猿学社 - https://ithub.blog.csdn.net/
 * Author: 程序猿学社
 * Date:  2020/2/22 11:08
 * Modified By:
 */
public class RUNNABLE {
    public static void main(String[] args) {
        Thread t = new Thread();
        t.start();
        System.out.println(t.getState());
    }
}

Here Insert Picture Description

TERMINATED (death or complete)

 package com.cxyxs.thread.five;

/**
 * Description:转发请注明来源  程序猿学社 - https://ithub.blog.csdn.net/
 * Author: 程序猿学社
 * Date:  2020/2/22 11:24
 * Modified By:
 */
public class TERMINATED {
    public static void main(String[] args) throws InterruptedException {
        Thread t = new Thread();
        t.start();
        Thread.sleep(5000);
        System.out.println(t.getState());
    }
}

Here Insert Picture Description
Combined with the code and the results RUNNABLE ready state, you Rotarians, why do I feel after an increase Thread.sleep, status codes will change slightly?
Before first answer this question, we need to understand the concept of time slices
start our method after calling thread is not executed immediately, but rather by resource scheduling cpu, assuming only one cpu, one channel, there are multiple threads simultaneously, because at the same time, there can be only one thread to grab resources, cpu will give this thread is allocated a time slice , if within a fixed time, has not been processed, in order to ensure a fair and impartial manner, cpu will cut a thread, fixed time processed, will cut a thread. This will not be a waste of resources.
- After the start, I was delayed five seconds, is to ensure that the thread has finished the race, so great has been the result TERMINATED

BLOCKED (blocking)

The current thread is waiting for a monitor lock process. Alternatively, for example, perform synchronized block synchronization method, causing threads in the clogged state.

package com.cxyxs.thread.five;

/**
 * Description:转发请注明来源  程序猿学社 - https://ithub.blog.csdn.net/
 * Author: 程序猿学社
 * Date:  2020/2/22 14:13
 * Modified By:
 */
public class BLOCKED {
    public static synchronized void  test() throws  Exception{
        //模拟业务
        Thread.sleep(3000);
    }

    public static void main(String[] args) throws  Exception{
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                try {
                    test();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };
        Thread thread = new Thread(runnable);
        thread.start();

        Thread thread1= new Thread(runnable);
        thread1.start();

        Thread.sleep(100);
        System.out.println(thread1.getState());
    }
}

Here Insert Picture Description
The code on two key steps

  • After the first step, start a synchronization method, which is equivalent to locked when multiple threads access, you need to get the qualifications lock in order to access the access.
  • The second step dormancy 100 milliseconds, this code is very important, it is to ensure that the thread is up and running.
    Case:
    next door to a small pit Wang, Wang go after it directly to the pit of Le were locked, others, need to wait for Wang after use, in order to enter. Other people to plug in here.

Several ways lead to blocking

  • The method of synchronization blocks or synchronization code
  • Object.wait

WAITING (waiting)

A thread wakes up waiting for another thread, this state is to wait.

package com.cxyxs.thread.five;

/**
 * Description:转发请注明来源  程序猿学社 - https://ithub.blog.csdn.net/
 * Author: 程序猿学社
 * Date:  2020/2/22 14:46
 * Modified By:
 */
public class WAITING {
    public static void main(String[] args) throws  Exception{
        Object locker = new Object();

        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                try {
                       synchronized (locker){
                           System.out.println("调用wait");
                           locker.wait();
                           System.out.println("调用wait后");
                       }
                       System.out.println("调用wait业务");
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };

        Thread t = new Thread(runnable);
        t.start();
        Thread.sleep(100);


        runnable = new Runnable() {
            @Override
            public void run() {
                try {
                    synchronized (locker){
                        System.out.println("调用notify");
                        locker.notify();
                        System.out.println("调用notify后");
                    }
                    System.out.println("调用notif业务");
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };
        Thread t1 = new Thread(runnable);
        t1.start();
        System.out.println(t.getState()+","+t1.getState());
    }
}

T1 thread by thread t wake, sleep 100 milliseconds, in order to ensure the thread is already running, calling thread t wait, the thread indicates that the thread enters the wait queue, the current thread t clog here not be run down, a need for additional thread wake him, synchronization lock is locker, after acquiring the lock, the call notify, wake up the thread t.
Here Insert Picture Description
may lead to a few WAITING

  • Object.wait
  • Thread.join
  • LockSupport.park
    were awakened by Object.notify

TIMED_WAITING (limit waiting)

A thread waits within a specific period of time to complete another thread is there such a state, automatic wake-up, called limited time to wait.

package com.cxyxs.thread.five;

/**
 * Description:转发请注明来源  程序猿学社 - https://ithub.blog.csdn.net/
 * Author: 程序猿学社
 * Date:  2020/2/22 13:42
 * Modified By:
 */
public class TIMEDWAITING{
    public static void main(String[] args) throws  Exception{
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                try {
                    //1
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        };
        Thread thread = new Thread(runnable);
        thread.start();
        //2  
        Thread.sleep(100);
        System.out.println(thread.getState());
    }
}

Here Insert Picture Description
The first step, a delay of 5 seconds, just to let the resources
second step, delayed 100 milliseconds, is to ensure that thread is already executing state. And to ensure that this thread to grab time slice.

Case:
next door Pharaoh intend to go to work, waiting for the bus, waited a long time, found no seat, thought, or did not get on the train, and finally, waiting for the next train, go to the company.
In fact, what I've got inside the cpu time slice resource qualifications, but because of the students, very lazy, I want a little uncomfortable, so he put the car on the qualifications give other people. Of course, the last, Amy did well to Trat company.

Several methods can lead to the following restrictions wait

  • Thread.sleep
  • Object.wait
  • Thread.join
  • LockSupport.parkNanos
  • LockSupport.parkUntil

Six states summary

Here Insert Picture Description
Here Insert Picture Description
Interview met asked lifecycle, from two graphs can start talking. Start with the following chart to start, and then the first figure. Start with great direction to begin with, and then to the underlying source code is how to achieve.

postscript

Next article will combine demo realized Thread understand some commonly used methods.

Published 276 original articles · won praise 496 · Views 200,000 +

Guess you like

Origin blog.csdn.net/qq_16855077/article/details/104439223