前言
如果一个知识点,学了10遍还不会!!那就学几十遍,几百遍……如果还学不会,那我不信!!!
线程的生命周期,以及线程的几个状态和状态之间的转化基本上每个人都能说上来,但是每个状态之间的转换,以及调用哪些方法可以由什么样的状态转换到什么样的状态还是有些模糊的。这次盘它!!!
线程的几种状态
比较细致的划分,线程总共有6中状态分别是:
- New
- Runnable
- Blocked
- Waiting (没有时间期限)
- Time Waiting (有时间期限)
- Terminated
线程6钟状态的变化,看图说话,一图胜过千言万语

代码调试
打印 NEW、RUNNABLE、TERMINATED状态
代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
|
public class ThreadLifeCycle implements Runnable{ public static void main(String[] args) { Thread thread = new Thread(new ThreadLifeCycle()); System.out.println(thread.getState()); thread.start(); System.out.println(thread.getState()); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(thread.getState()); } public void run() { for (int i = 0; i < 1000; i++) {
} } }
|
打印结果

打印 Time Waiting、Waiting、BLOCKED状态
因为多线程代码不好调试,可以根据代码中的注释自己开启多线程调试打印出线程的各个状态!!!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
|
public class ThreadLifeCycle1 implements Runnable {
public static void main(String[] args) { ThreadLifeCycle1 runable = new ThreadLifeCycle1(); Thread thread1 = new Thread(runable); thread1.start(); Thread thread2 = new Thread(runable); thread2.start(); System.out.println(thread1.getState()); try { Thread.sleep(1300); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(thread1.getState()); System.out.println(thread2.getState());
} public void run() { sync(); } private synchronized void sync() { try { Thread.sleep(10000); wait(); } catch (InterruptedException e) { e.printStackTrace(); } } }
|
总结
以上就是线程的各个状态,以及调用哪些方法会触发线程的转换,总结的很全面了!!!
一般而言Blocked、Waiting、Time Waiting这些状态都会被称为阻塞状态,不仅仅是Blocked
你知道的越多,你不知道的越多
欢迎扫码关注
如果喜欢请关注我公众号【程序倾听者】,说出你的故事!我在这里倾听!

顶我一下下!