前言
从编写Java代码的角度来说,线程一共有六种状态;但是以操作系统的视角来看,线程状态可以分为物种
六种划分
调用getState()方法获取当前线程状态
一.NEW
定义:线程(对象)被创建但还没有启动
java">public class NEW {public static void main(String[] args) {Thread thread = new Thread(()->{});//thread创建完毕//NEWSystem.out.println(thread.getState());}
}
二.RUNNABLE
定义:线程创建并启动完毕,拥有执行代码的能力或者正在执行代码
java">public class RUNNABLE {public static void main(String[] args) throws InterruptedException {Thread thread = new Thread(()->{while (true){try {Thread.sleep(500);} catch (InterruptedException e) {throw new RuntimeException(e);}System.out.println("Hello Thread");}});//调用startthread.start();//RUNNABLESystem.out.println(thread.getState());}
}
三.WAITING
定义:线程处于等待状态,等待其他线程执行完毕(join)或者其他线程来唤醒(notify)
java">public class WAITING {public static void main(String[] args) throws InterruptedException {Object locker = new Object();Thread thread = new Thread(()->{synchronized (locker){try {//无时间参数的waitlocker.wait();} catch (InterruptedException e) {throw new RuntimeException(e);}}});thread.start();Thread.sleep(100);//WAITINGSystem.out.println(thread.getState());}
}
四.TIMED_WAITING
定义:线程处于等待状态
-
等待其他线程执行完毕(join)
-
其他线程来唤醒(notify)
-
等待一定的时间后自动唤醒
java">public class TIMED_WAITING {public static void main(String[] args) throws InterruptedException {Object locker = new Object();Thread thread = new Thread(()->{synchronized (locker){try {//有时间参数的waitlocker.wait(10000000);} catch (InterruptedException e) {throw new RuntimeException(e);}}});thread.start();Thread.sleep(100);//System.out.println(thread.getState());}
}
五.BLOCKED
定义:线程竞争锁对象失败进入BLOCKED(锁竞争)状态
java">public class BLOCKED {public static void main(String[] args) throws InterruptedException {Object locker = new Object();Thread thread1 = new Thread(()->{synchronized (locker){try {Thread.sleep(1000000);} catch (InterruptedException e) {throw new RuntimeException(e);}}});thread1.start();//thread1先拿到locker锁对象Thread thread2 = new Thread(()->{while (true) {synchronized (locker) {System.out.println("Hello Thread2");}}});thread2.start();//sleep(1000)的作用是让thread2有足够用的时间执行到synchronizedThread.sleep(100);//获取线程状态//BLOCKEDSystem.out.println(thread2.getState());}
}
六.TERMINATED
定义:线程执行完毕或者因异常退出
java">public class TERMINATED {public static void main(String[] args) throws InterruptedException {Thread thread = new Thread(()->{});thread.start();//等待线程执行完毕thread.join();//TERMINATEDSystem.out.println(thread.getState());}
}
五种划分
一.新建
和NEW一样
二.就绪
CPU已经为线程分配好了时间,但还没来得及执行代码
三.运行
CPU已经为线程分配好了时间,并且正在执行代码
四.阻塞
线程启动完毕,但被暂停执行(可能是自身原因,也可能是外部原因),有以下几种情况
1.等待其他线程释放锁对象
2.等待文件IO,如
3.调用wait(无参数/有参数)方法
五.终止
和TERMINATED一样,线程执行完毕或者被强制终止