五种状态
- 初始状态
实例化一个新 Thread 对象且尚未调用此实例的 start 方法时
- 可运行状态
调用了 Thread 对象的 start 方法,但是操作系统尚未给它分配时间片时
- 运行状态
操作系统给 Thread 对象分配了时间片
- 阻塞状态
当 Thread 对象调用了某些阻塞方法时
- 终止状态
当 Thread 对象执行完毕时
五种状态可以像图中所示进行转换
六种状态
Thread.State 里的六种状态
- New
实例化一个新 Thread 对象且尚未调用此实例的 start 方法时
- Runnable
运行和可以运行的状态统称,同时线程执行阻塞IO操作时也认为是本状态
- Blocked
阻塞
- Waiting
Join
- Timed_Waiting
Sleep
- Terminated
当 Thread 对象执行完毕时
参考代码
@Slf4j
public class Test3 {
public static void main(String[] args) {
// New 但未 start
Thread t1 = new Thread(()->{
log.debug("running...");
}, "t1");
// Running -> Runnable
Thread t2 = new Thread(()->{
while (true) {
}
}, "t2");
t2.start();
// Terminated
Thread t3 = new Thread(()->{
log.debug("running...");
}, "t3");
t3.start();
// sleep -> Timed_Waiting
Thread t4 = new Thread(()->{
synchronized (Test3.class) {
try {
TimeUnit.SECONDS.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}, "t4");
t4.start();
// Waiting
Thread t5 = new Thread(()->{
try {
t2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}, "t5");
t5.start();
// Blocked 抢占锁
Thread t6 = new Thread(()->{
synchronized (Test3.class) {
try {
TimeUnit.SECONDS.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}, "t6");
t6.start();
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
log.debug("t1 state {}", t1.getState());
log.debug("t2 state {}", t2.getState());
log.debug("t3 state {}", t3.getState());
log.debug("t4 state {}", t4.getState());
log.debug("t5 state {}", t5.getState());
log.debug("t6 state {}", t6.getState());
}
}
执行结果:
t1 state NEW
t2 state RUNNABLE
t3 state TERMINATED
t4 state TIMED_WAITING
t5 state WAITING
t6 state BLOCKED