一、五种状态与六种状态
1.针对操作系统层面
线程的五种状态2.针对Java API层面
线程的六种状态
-
NEW
初始状态,线程刚创建,没有调用start()方法
public static void main(String[] args) {
Thread t1 = new Thread(() -> log.debug("{}","running..."),"t1");
log.debug("{}",t1.getState());
}
输出结果:
14:43:34.132 [main] - NEW
-
RUNNABLE
可运行线程的线程状态。处于可运行状态的线程正在Java虚拟机中执行,但它可能正在等待来自操作系统(如处理器)的其他资源。
public static void main(String[] args) {
Thread t1 = new Thread(() -> log.debug("{}","running..."),"t1");
t1.start();
log.debug("{}",t1.getState());
}
输出结果:
14:46:48.324 [main] - RUNNABLE
-
BLOCKED
等待监视器锁的阻塞线程的线程状态。
public static void main(String[] args) throws InterruptedException {
Thread t1 = new Thread(() -> {
synchronized (New.class){
while (true){
}
}
},"t1");
t1.start();
Thread t2 = new Thread(() ->{
synchronized (New.class){
log.debug("{}","running");
}
});
t2.start();
TimeUnit.SECONDS.sleep(1);
log.debug("{}",t2.getState());
}
输出结果:
15:01:33.626 [main] - BLOCKED
-
WAITING
等待线程的线程状态,调用wait(),join(),park()方法都会进入此状态
public static void main(String[] args) throws InterruptedException {
Thread t1 = new Thread(() ->{
while (true){
}
},"t1");
t1.start();
Thread t2 = new Thread(() ->{
try {
//t2同步等待t1线程
t1.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
},"t2");
t2.start();
TimeUnit.SECONDS.sleep(1);
log.debug("{}",t2.getState());
}
输出结果:
15:20:30.439 [main] - WAITING
-
TIMED_WAITING
具有指定等待时间的等待线程的线程状态。调用sleep(),wait(),join(),parkNanos,parkUntil指定时间会进入此状态
public static void main(String[] args) throws InterruptedException {
Thread t1 = new Thread(() ->{
try {
TimeUnit.SECONDS.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
},"t1");
t1.start();
TimeUnit.SECONDS.sleep(1);
log.debug("{}",t1.getState());
}
输出结果:
15:20:51.507 [main] - TIMED_WAITING
-
TERMINATED
终止线程的线程状态。线程已完成执行。
public static void main(String[] args) throws InterruptedException {
Thread t1 = new Thread(() -> log.debug("{}","running..."),"t1");
t1.start();
TimeUnit.SECONDS.sleep(1);
log.debug("{}",t1.getState());
}
输出结果:
15:27:18.540 [main] - TERMINATED
网友评论