1. New 已创建对象,还未调用start()
//New 状态 public class Demo01 { public static void main(String[] args) { Thread t = new Thread(()->{ }); System.out.println(t.getState());//获取线程状态 t.start(); } } NEW Process finished with exit code 0
2. Runnable 就绪状态 (准备随时上CPU)
//Runnable 就绪状态 public class Demo03 { public static void main(String[] args) throws InterruptedException { Thread t = new Thread(()->{ while(true){ //此时线程一直在准备执行,随时上CPU,处于就绪状态 } }); t.start(); Thread.sleep(1000); System.out.println(t.getState()); } } RUNNABLE Process finished with exit code 130
3. Timed_Waiting 在一定时间内,线程是阻塞的
线程内容中加入sleep()、join(超时时间),程序就会进入此状态
//Time_Waiting 在一定时间内,线程是阻塞的 public class Demo04 { public static void main(String[] args) throws InterruptedException { Thread t = new Thread(()->{ while(true){ try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } }); t.start(); Thread.sleep(1000); System.out.println(t.getState()); } } TIMED_WAITING Process finished with exit code 130
4. Blocked 当前线程在等待锁,导致线程阻塞
使用synchronized会触发此状态
5. Waiting 当前线程在等待唤醒,导致了阻塞
使用wait会触发此状态
6. Terminated 线程执行完毕
//terminated 线程已经执行完毕 public class Demo02 { public static void main(String[] args) throws InterruptedException { Thread t = new Thread(()->{ }); t.start(); Thread.sleep(1000); System.out.println(t.getState()); } } TERMINATED Process finished with exit code 0
7. 线程状态转换图