Java多线程-生命周期
# Java多线程04-生命周期
线程共有六种生命周期,分别是:
- New(新创建)
- Runnable (可运行)
- Blocked (被阻塞)
- Waiting (等待)
- Timed Waiting (记时等待)
- Terminated (已终止)
六大生命周期转换图如下:
#
# 线程状态变化案例
演示NEW、RUNNABLE、Terminated状态:
public class NewRunnableTerminated implements Runnable{
public static void main(String[] args) {
Thread thread = new Thread(new NewRunnableTerminated());
System.out.println(thread.getState());
thread.start();
System.out.println(thread.getState());
try {
Thread.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
//打印出RUNNABLE的状态,即使是正在运行,也是RUNNABLE,而不是RUNNING
System.out.println(thread.getState());
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
//打印出TERMINATED状态
System.out.println(thread.getState());
}
@Override
public void run() {
for (int i = 0; i < 1000; i++) {
System.out.println(i);
}
}
}
演示Blocked、Waiting、TimedWaiting状态:
public class NewRunnableTerminated implements Runnable{
public static void main(String[] args) {
Thread thread = new Thread(new NewRunnableTerminated());
System.out.println(thread.getState());
thread.start();
System.out.println(thread.getState());
try {
Thread.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
//打印出RUNNABLE的状态,即使是正在运行,也是RUNNABLE,而不是RUNNING
System.out.println(thread.getState());
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
//打印出TERMINATED状态
System.out.println(thread.getState());
}
@Override
public void run() {
for (int i = 0; i < 1000; i++) {
System.out.println(i);
}
}
}
上次更新: 2024/06/29, 15:13:44