一、线程六种状态

线程可以有如下 6 种状态:
•New (新创建)
•Runnable (可运行)
•Blocked (被阻塞)
•Waiting (等待)
•Timed waiting (计时等待)
•Terminated (被终止)
要确定一个线程的当前状态, 可调用Thread的getState()方法。

New (新创建)

Thread state for a thread which has not yet started.

当用 new 操作符创建一个新线程时,如 newThread®, 该线程还没有开始运行。这意味着它的状态是 new。当一个线程处于新创建状态时,程序还没有开始运行线程中的代码。在线程运行之前还有一些基础工作要做。

Runnable (可运行)

Thread state for a runnable thread. A thread in the runnable state is executing in the Java virtual machine but it may be waiting for other resources from the operating system such as processor.

(Java线程中将就绪(ready)和运行中(running)两种状态笼统的称为Runnable。该状态的线程位于可运行线程池中,等待被线程调度选中,当没有被线程调度选中时处于就绪状态(ready),就绪状态的线程在被线程调度选中时获得CPU时间片后变为运行中状态(running)。 )

一旦调用了start()方法,线程处于Runnable状态。一个可运行的线程可能正在运行也可能没有在运行,这取决于操作系统是否给线程提供运行的时间,一个运行中的线程仍然处于Runnable 状态。

一旦一个线程开始运行,它不必始终在运行。线程调度的细节依赖于操作系统提供的服务。抢占式调度系统给每一个可运行线程一个时间片来执行任务。当时间片用完,操作系统剥夺该线程的运行权, 并给另一个线程运行机会。当选择下一个线程时, 操作系统考虑线程的优先级。

现在所有的桌面以及服务器操作系统都使用抢占式调度。但是,像手机这样的小型设备可能使用协作式调度。在这样的设备中,一个线程只有在调用 yield 方法、 或者被阻塞或等待时,线程才失去控制权。

在具有多个处理器的机器上,每一个处理器运行一个线程, 可以有多个线程并行运行。当然,如果线程的数目多于处理器的数目,调度器依然采用时间片机制。

记住,在任何给定时刻,一个可运行的线程可能正在运行也可能没有在运行(这也就是为什么将这个状态称为可运行而不是运行)。

Blocked (被阻塞)

Thread state for a thread blocked waiting for a monitor lock. A thread in the blocked state is waiting for a monitor lock to enter a synchronized block/method or reenter a synchronized block/method after calling Object.wait.

当一个线程试图获取一个内部的对象锁(而不是 java.util.concurrent库中的锁) 而该对象锁被其他线程持有, 则该线程进人阻塞状态。

Waiting (等待)

Thread state for a waiting thread. A thread is in the waiting state due to calling one of the following methods:

  • Object.wait with no timeout
  • Thread.join with no timeout
  • LockSupport.park

A thread in the waiting state is waiting for another thread to perform a particular action. For example, a thread that has called Object.wait() on an object is waiting for another thread to call Object.notify() or Object.notifyAll() on that object. A thread that has called Thread.join() is waiting for a specified thread to terminate.

进入该状态的线程需要等待其他线程做出一些特定动作。

Timed waiting (计时等待)

public static final Thread.State TIMED_WAITING
Thread state for a waiting thread with a specified waiting time. A thread is in the timed waiting state due to calling one of the following methods with a specified positive waiting time:

  • Thread.sleep
  • Object.wait with timeout
  • Thread.join with timeout
  • LockSupport.parkNanos
  • LockSupport.parkUntil

Terminated (被终止)

Thread state for a terminated thread. The thread has completed execution.

线程已经终止。线程有如下两个原因之一而被终止:

  1. run()执行完正常退出而自然死亡。
  2. 因为一个没有捕获的异常终止了run()方法而异常死亡。

这6种状态定义在Thread类的State枚举中,可查看源码进行一一对应。

二、线程的状态转换图

java thread表达式 java thread state_java thread表达式


下图是 Java 核心技术 卷一 里的一张线程状态图:

java thread表达式 java thread state_Java_02

参考:
https://docs.oracle.com/en/java/javase/13/docs/api/java.base/java/lang/Thread.State.htmlJava核心技术 卷一