目录
线程的状态
线程的状态有这六种:
NEW RUNNABLE TIME_WAITING WAITING BLOCKED TERMINATED

有了上面这个图,线程的状态就一目了然了。
获取线程状态的方法
| 方法 | 说明 |
| getState() | 这是个实例方法,该方法返回的是枚举类型。枚举的内容就是上面的那六个状态。 |
public class ThreadDemo12 {
public static void main(String[] args) throws InterruptedException {
Thread t12 = new Thread(() -> {
for (int i = 0; i < 10; i++) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
System.out.println("t12线程开始前:");
System.out.println(t12.getState());
System.out.println("t12线程开始后:");
t12.start();
for (int i = 0; i < 10; i++) {
System.out.println(t12.getState());
Thread.sleep(1);
}
t12.join();
System.out.println("t12线程结束了!");
System.out.println(t12.getState());
}
}

使用Jconsole观察线程
现在运行以下一个程序,同时使用jdk里面的工具Jconsole来观察线程。
public class ThreadDemo13 {
public static void main(String[] args) {
Thread t13 = new Thread(() -> {
while (true) {
}
});
t13.start();
while (true) {
}
}
}



该工具就在jdk里面。

有什么错误评论区指出,希望可以帮到你。
文章介绍了Java线程的六种状态,包括NEW、RUNNABLE、TIME_WAITING、WAITING、BLOCKED和TERMINATED,并通过示例代码展示了如何使用Thread的getState()方法获取线程状态。此外,还演示了利用Jconsole工具实时观察线程状态的应用。
726

被折叠的 条评论
为什么被折叠?



