在回顾Java线程相关知识点时,发现互联网上很多不负责任的文章将Java线程状态与操作系统线程状态混为一谈,极为混乱,极大的误导了读者;故在此做一个详细的梳理;也望读者不要轻易相信互联网上的文章,最好亲自查证。

前言

在回顾Java线程相关知识点时,发现互联网上很多不负责任的文章将Java线程状态与操作系统线程状态混为一谈,极为混乱,极大的误导了读者;故在此做一个详细的梳理;也望读者不要轻易相信互联网上的文章,最好亲自查证。

虚拟机线程状态 vs 操作系统线程状态

Java线程状态指的是虚拟机层面暴露给开发者使用的状态,由Thread.State类定义。底层由于操作系统的千差万别,各操作系统对于线程也有不同的状态,有可能操作系统线程多个状态对应一个Java线程状态;虚拟机的存在就是统一了底层的这些差别,让开发者不必关心这些问题。

Java线程状态

自JDK1.5开始,Java在Thread;且在给定时间点上,一个线程只能处于这6种状态中的一种。

  • NEW

    Thread state for a thread which has not yet started.

  • 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.

  • BOLCKED

    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 callingObject.wait.

  • 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

    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.

Oracle官方文档片段

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public static enum Thread.State
extends Enum<Thread.State>
A thread state. A thread can be in one of the following states:
NEW
A thread that has not yet started is in this state.
RUNNABLE
A thread executing in the Java virtual machine is in this state.
BLOCKED
A thread that is blocked waiting for a monitor lock is in this state.
WAITING
A thread that is waiting indefinitely for another thread to perform a particular action is in this state.
TIMED_WAITING
A thread that is waiting for another thread to perform an action for up to a specified waiting time is in this state.
TERMINATED
A thread that has exited is in this state.
A thread can be in only one state at a given point in time. These states are virtual machine states which do not reflect any operating system thread states.
Since:
1.5

Java线程状态迁移

ThreadStateTranform

Java线程常用方法