案例:
package com.xyc.demo1;
/**
* 2020/4/6 18:23
* 文件说明:
* 监测线程状态
* @author 太阳以西
* 梦可以到的地方,只要努力,总有一天,自己也可以达到!
*/
public class TestState {
public static void main(String[] args) throws InterruptedException {
// lambda表达式 创建一个临时线程
Thread thread = new Thread(() -> {
for (int i = 0; i < 5; i++) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+i);
}
System.out.println("循环结束。。。");
},"a--->");
//观察状态
Thread.State state = thread.getState();
System.out.println(state);
//启动线程后
thread.start();
state = thread.getState();
System.out.println(state);
while (state!=Thread.State.TERMINATED||!state.equals(Thread.State.TERMINATED)){
Thread.sleep(500);
state=thread.getState();
System.out.println(state);
}
}
}