线程的几种状态

MaxWen

关注

阅读 81

2022-03-26

目录

🍉线程的几种状态

🍉NEW(线程未调用状态)

🌰 :

public class TestDemo9 {
    public static void main(String[] args) {
        Thread thread = new Thread(()->{
            
        });
        System.out.println(thread.getState());
        thread.start();
    }
}

请添加图片描述

🍉TERMINATED(线程完成状态)

🌰 :

public class TestDemo9 {
    public static void main(String[] args) throws InterruptedException {
        Thread thread = new Thread(()->{

        });
        thread.start();
        System.out.println(thread.getState());
        Thread.sleep(1000);
        System.out.println(thread.getState());
    }
}

此时,我们会返现代码中存在sleep()方法,这是因为main()与线程thread是并发执行的,不加sleep()所获取的就是main()线程的状态
请添加图片描述

🍉RUNNABLE(就绪状态)

🌰 `

public class TestDemo9 {
    public static void main(String[] args) throws InterruptedException {
        Thread thread = new Thread(()->{
            while(true){
                //此处什么都不能有,因为不确定代码要进行什么操作,如果进行了堵塞操作,代码就不是就绪状态了
            }
        });
        thread.start();
        Thread.sleep(1000);
        System.out.println(thread.getState());
    }
}

请添加图片描述

🍉阻塞状态

🍉TIMED_WAITING

🌰

public class TestDemo9 {
    public static void main(String[] args) throws InterruptedException {
        Thread thread = new Thread(()->{
            while(true){
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        thread.start();
        Thread.sleep(1000);
        System.out.println(thread.getState());
    }
}

请添加图片描述

🍉BLOCKED

🍉WAITING

请添加图片描述

🥝 为什么要了解线程的这几种状态

精彩评论(0)

0 0 举报