人有生来病死,线程一样,线程主要有创建、就绪、运行、阻塞、死亡这五个状态。
测试线程状态
public class 测试线程状态 {
public static void main(String[] args) throws InterruptedException {
Thread thread = new Thread(()-> {
for(int i = 0 ; i < 10 ; i++) {
try {
Thread.sleep(1000);
} catch (Exception e) {
e.printStackTrace();
}
}
System.out.println("//线程执行完毕//"); // ---->TERMINATED
});
//观察状态
Thread.State state = thread.getState();
System.out.println(state); // ----> NEW
//观察启动后
thread.start(); //启动线程
state = thread.getState(); //更新线程状态
System.out.println(state); // ---->RUNNABLE
while(state != Thread.State.TERMINATED) { //只要线程不终止,就一直输出状态
Thread.sleep(1000);
state = thread.getState();//更新状态
System.out.println(state);//输出状态 ---->TIME_WAITING
}
}
}