观测线程状态-java

观测线程状态

观测线程状态-java_第1张图片
观测线程状态-java_第2张图片

线程状态有的书籍叫线程生命周期。通过代码演示,观测线程状态:

创建线程myThread用到了lambda表达式,详细了解点击这里:传送门。

//观察线程的状态
public class TestState {
    public static void main(String[] args) throws InterruptedException {
        Thread myThread = new Thread(()->{//创建线程myThread
            for (int i = 0; i < 3; i++) {
                try {
                    Thread.sleep(1000);//该方法,三秒钟打印三句话
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("myThread:hello world!");

            }
            System.out.println("myThread:--线程结束--");
        });

        //观察状态
        Thread.State state = myThread.getState();
        System.out.println(state);//线程刚刚创建,此时的状态是NEW

        //观察启动后的状态
        myThread.start();//启动线程
        state = myThread.getState();
        System.out.println(state);//查看线程状态,此时线程应该处于运行状态RUNNABLE(线程myThread中设置了线程休眠,不会那么快结束)

        while (state != Thread.State.TERMINATED){//线程还没终止,则进入该循环。输出线程的状态
            Thread.sleep(2000);
            state = myThread.getState();
            System.out.println(state);
        }
    }
}
  • 线程刚刚创建还没启动时,此时的状态是NEW
  • 线程正在运行,此时的状态是RUNNABLE
  • CPU调用了main线程中的System.out.println(state),故此时线程myThread的状态是TIMED_WAITING
  • 线程执行结束后,此时的状态是TERMINATED

运行结果:

NEW
RUNNABLE
myThread:hello world!
TIMED_WAITING
myThread:hello world!
myThread:hello world!
myThread:--线程结束--
TERMINATED

Process finished with exit code 0

学习自B站遇见狂神说
相关博客:多线程-汇总

你可能感兴趣的:(多线程-Java,java,多线程,线程状态)