网站建设公司net2006,制作书签二年级,建筑工程有限公司招聘信息,群晖做网站域名5种状态一般是针对传统的线程状态来说#xff08;操作系统层面#xff09; 6种状态#xff1a;Java中给线程准备的 NEW#xff1a;Thread对象被创建出来了#xff0c;但是还没有执行start方法。
RUNNABLE#xff1a;Thread对象调用了start方法#xff0c;就为RUNNABLE状…5种状态一般是针对传统的线程状态来说操作系统层面 6种状态Java中给线程准备的 NEWThread对象被创建出来了但是还没有执行start方法。
RUNNABLEThread对象调用了start方法就为RUNNABLE状态CPU调度/没有调度
BLOCKED、WAITING、TIME_WAITING都可以理解为是阻塞、等待状态因为处在这三种状态下CPU不会调度当前线程
BLOCKEDsynchronized没有拿到同步锁被阻塞的情况
WAITING调用wait方法就会处于WAITING状态需要被手动唤醒
TIME_WAITING调用sleep方法或者join方法会被自动唤醒无需手动唤醒
TERMINATEDrun方法执行完毕线程生命周期到头了
在Java代码中验证一下效果
NEW
public static void main(String[] args) throws InterruptedException {Thread t1 new Thread(() - {});System.out.println(t1.getState());
}
RUNNABLE
public static void main(String[] args) throws InterruptedException {Thread t1 new Thread(() - {while(true){}});t1.start();Thread.sleep(500);System.out.println(t1.getState());
}
BLOCKED
public static void main(String[] args) throws InterruptedException {Object obj new Object();Thread t1 new Thread(() - {// t1线程拿不到锁资源导致变为BLOCKED状态synchronized (obj){}});// main线程拿到obj的锁资源synchronized (obj) {t1.start();Thread.sleep(500);System.out.println(t1.getState());}
}
WAITING
public static void main(String[] args) throws InterruptedException {Object obj new Object();Thread t1 new Thread(() - {synchronized (obj){try {obj.wait();} catch (InterruptedException e) {e.printStackTrace();}}});t1.start();Thread.sleep(500);System.out.println(t1.getState());
}
TIMED_WAITING
public static void main(String[] args) throws InterruptedException {Thread t1 new Thread(() - {try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}});t1.start();Thread.sleep(500);System.out.println(t1.getState());
}
TERMINATED
public static void main(String[] args) throws InterruptedException {Thread t1 new Thread(() - {try {Thread.sleep(500);} catch (InterruptedException e) {e.printStackTrace();}});t1.start();Thread.sleep(1000);System.out.println(t1.getState());
}
知识来源
【2023年面试】Java面向对象有哪些特征_哔哩哔哩_bilibili