Java 中线程的生命周期通常包括以下几个状态:
- 新建状态 (New):线程被创建,但尚未启动。
- 就绪状态 (Runnable):线程已经启动,但等待操作系统调度执行。
- 运行状态 (Running):线程正在执行。
- 阻塞状态 (Blocked):线程由于某些原因(如等待锁)被阻塞,无法继续执行。
- 等待状态 (Waiting):线程等待某些条件发生才能继续执行,通常是通过
wait()、join()等方法。 - 超时等待状态 (Timed Waiting):线程在指定时间内等待某个条件,超时后会自动返回。
- 终止状态 (Terminated):线程执行完毕或被中止。
下面是一个简单的 Java 代码示例,展示了线程生命周期的各个阶段:
class ThreadLifecycleDemo extends Thread {
@Override
public void run() {
try {
System.out.println(Thread.currentThread().getName() + " is in Running state.");
// Simulate some work
Thread.sleep(2000); // This will cause the thread to go into Timed Waiting state
System.out.println(Thread.currentThread().getName() + " finished sleeping.");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws InterruptedException {
// Step 1: New state
ThreadLifecycleDemo thread = new ThreadLifecycleDemo();
System.out.println("Thread state after creation: " + thread.getState());
// Step 2: Start thread - Runnable state
thread.start();
System.out.println("Thread state after start: " + thread.getState());
// Wait for the thread to sleep and then finish
Thread.sleep(500); // This allows the thread to enter a running state before checking again
// Step 3: Checking state while thread is running
System.out.println("Thread state while running (before sleep): " + thread.getState());
// Wait until the thread finishes its work
thread.join(); // This makes the main thread wait for 'thread' to complete
// Step 4: After thread finishes - Terminated state
System.out.println("Thread state after completion: " + thread.getState());
}
}
代码解析:
-
新建状态 (New):在调用
new ThreadLifecycleDemo()时,线程对象还没有启动,此时线程处于新建状态。 -
就绪状态 (Runnable):调用
thread.start()后,线程进入就绪状态,等待操作系统调度执行。 -
运行状态 (Running):线程开始执行
run()方法中的代码,在Thread.sleep(2000)时,线程进入了“超时等待”状态。 -
超时等待状态 (Timed Waiting):
Thread.sleep(2000)会使线程进入等待状态,直到指定时间过去。 -
终止状态 (Terminated):当
run()方法执行完毕,线程进入终止状态。
线程状态的输出:
- 在创建线程时,输出:
Thread state after creation: NEW - 在启动线程后,输出:
Thread state after start: RUNNABLE - 当线程运行并在
sleep()时,输出:Thread state while running (before sleep): TIMED_WAITING - 线程执行完毕后,输出:
Thread state after completion: TERMINATED
909

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



