线程的6种状态[编程语言教程]

Thread类中定义了一个枚举类型State,描述了线程的6种状态

public enum State {
    NEW,
    RUNNABLE,
    BLOCKED,
    WAITING,
    TIMED_WAITING,
    TERMINATED;
}

jdk1.8 api对Thread.State的解释,详见官网api

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.

通过new Thread()创建一个线程,这时候线程处于NEW状态

调用Thread类的start()方法后,线程处于RUNNABLE状态

线程需要执行同步代码块,而这个时候其他线程没有释放锁,线程处于BLOCKED状态

CPU不会分配执行时间给处在WAITING状态的线程,处在这种状态的线程需要其他线程显示的唤醒

TIMED_WAITING状态的线程会在到达指定时间后自动唤醒

线程执行完run()方法中的代码或者被破终止后处于TERMINATED状态,这种状态下的线程不能再运行

查看线程状态

Thread类中定义了一个getState()方法,可以用来查看线程的状态

public State getState()

线程的6种状态

原文:https://www.cnblogs.com/qixioa/p/13643144.html

hmoban主题是根据ripro二开的主题,极致后台体验,无插件,集成会员系统
自学咖网 » 线程的6种状态