// Java线程状态示例代码
public class ThreadStatesExample {
public static void main(String[] args) throws InterruptedException {
// 创建一个线程
Thread thread = new Thread(() -> {
try {
// 线程进入运行状态
System.out.println("Thread is running...");
Thread.sleep(5000); // 线程进入等待/阻塞状态
System.out.println("Thread woke up...");
} catch (InterruptedException e) {
e.printStackTrace();
}
});
// 线程初始状态为新建(New)
System.out.println("Thread state: " + thread.getState());
// 启动线程,线程进入就绪(Runnable)状态
thread.start();
// 让主线程稍作等待,以观察其他线程状态
Thread.sleep(100);
// 打印线程的当前状态
System.out.println("Thread state after starting: " + thread.getState());
// 等待子线程执行完毕
thread.join();
// 打印线程的最终状态
System.out.println("Thread state after joining: " + thread.getState());
}
}
sleep
方法或等待锁。通过这段代码,你可以看到线程从新建到终止的各个状态变化。
上一篇:java匿名内部类
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站