自学内容网 自学内容网

线程的状态

在Java中线程一共有六种状态。
①:NEW
当前Thread对象有了,但是内核还没有(没有调用start);

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

在这里插入图片描述

此处t.getState()就会是NEW;

②:TERMINATED
当前Thread对象还在,但是内核的线程已经销毁(线程结束了);

public class Demo3 {
    public static void main(String[] args) throws InterruptedException {
        Thread t = new Thread(() -> {
            System.out.println("hello thread");
        });
        System.out.println(t.getState());
        t.start();
        Thread.sleep(200);
        System.out.println(t.getState());
    }
}

在这里插入图片描述
此处就会是TERMINATED,sleep是为了让t线程结束;

③:RUNNABLE
就绪状态,正在CPU上运行 + 随时可以调度到CPU上运行;

public class Demo3 {
    public static void main(String[] args) throws InterruptedException {
        Thread t = new Thread(() -> {
            while(true) {

            }
        });
        System.out.println(t.getState());
        t.start();
        System.out.println(t.getState());
    }
}

在这里插入图片描述
此处调用start之后,t线程就一直在CPU上运行,因为有个while循环,所以会是RUNNABLE;

④:BLOCKED
因为锁竞争,而引起的阻塞;

⑤:TIME_WATING
有超时时间的等待,比如sleep,join的有参数版本;

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

在这里插入图片描述
此时当调用start之后,main线程会进入sleep(200),以此来确保t线程在sleep(1000)之中,所以此时t线程的状态就是TIME_WATING;

⑥:WATING
没有超时时间的等待,例如join的无参数版本,wait…,是针对于等待的那个线程;

public class Demo3 {
    public static void main(String[] args) throws InterruptedException {
        Thread mainThread = Thread.currentThread();
        Thread t = new Thread(() -> {
            while(true) {
                try {
                    System.out.println(mainThread.getState());
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });
        t.start();
        t.join();
    }
}

在这里插入图片描述
此处,是main线程等待t线程,所以对于main线程来说,main线程的状态是WATING。

以上就是线程的六种状态,其中4,5,6是一类阻塞状态,而第六种状态是针对等待的线程,而不是被等待的线程。


原文地址:https://blog.csdn.net/2301_80427749/article/details/142468902

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!