线程状态
五大状态:
照片来源:狂神
测试代码:
package com.heima.Multithreading;
//观察测试线程的状态
public class TestState {
public static void main(String[] args) throws InterruptedException {
Thread thread = new Thread(()->{
for (int i = 0; i < 5; i++) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("--------");
});
//观测状态
Thread.State state = thread.getState();//有点内部类的味道
System.out.println(state);//new
//观察启动后
thread.start();
state = thread.getState();//更新
System.out.println(state);
//继续观察启动后的状态
while(state != Thread.State.TERMINATED){//只要线程不停止就一直输出状态
Thread.sleep(100);//增加延时,只需一秒输出10次即可
state = thread.getState();//跟新状态
System.out.println(state);
}
thread.start();
}
}
结果显示:
线程结束后不能重新启动