前言
首先来聊为什么会对Java线程状态这个东西作一个博客的梳理,主要是因为看到很多网上的帖子对线程的状态定义了很多五花八门的状态,有的还是中文。这会对很多初学者造成误导。所以我在这里把JDK中Thread.java的源码翻出来,里面的内部枚举类(public enum State)定义了Java虚拟机对Thread State的六种定义构成了Java线程的生命周期,它们分别是:NEW,RUNABLE,BLOCKED,WATING,TIMED_WATING,TERMINATED。
Java Thread 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.原文的意思是一个线程在给定的时间点只有一种状态,这些状态是线程在虚拟机里面的状态,不能反映任何操作系统中线程的状态。
1、NEW(创建):A thread that has not yet started is in this state.原文的意思是Thread被创建后,还没有执行start方法之前就是NEW 状态。
2、RUNABLE(可运行):A thread executing in the Java virtual machine is in this state.原文的意思是线程已经在Java虚拟机里面执行中(executing )就是在RUNABLE 状态。这个解释很多人会理解有偏差,再看下面一段。
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.这段原文的意思是可运行状态的线程是在虚拟机里面执行中,但是有可能等待其它来自操作系统的资源,比如:处理器。
3、BLOCKED(阻塞):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.原文的意思是一个阻塞线程正在等待一个监视器锁为了可以进入一个同步代码块/方法块或者重入(再次进入)一个同步代码块/方法。
4、WATING(等待):A thread is in the waiting state due to calling one of the following methods: Object.wait with no timeout,Thread.join with no timeoutLockSupport.park.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.原文的意思是一个等待线程主要是因为调用了这三个方法,等待其它线程执行一个特定的动作。举个栗子,一个线程调用了对象的wait方法实在等待其它线程调用该对象的notify 或者notifyAll方法,一个线程调用了Thread.join方法实在等待它指定的线程终止。
5、TIMED_WATING(定时等待):
/**
* 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:
* <ul>
* <li>{@link #sleep Thread.sleep}</li>
* <li>{@link Object#wait(long) Object.wait} with timeout</li>
* <li>{@link #join(long) Thread.join} with timeout</li>
* <li>{@link LockSupport#parkNanos LockSupport.parkNanos}</li>
* <li>{@link LockSupport#parkUntil LockSupport.parkUntil}</li>
* </ul>
*/
注释的意思大概是定时等待是因为线程调用了以下的方法,会等待到给定的时间。
6、TERMINATED(终止)
/**
* Thread state for a terminated thread.
* The thread has completed execution.
*/
总之,还是推荐大家去看Thread.java的源码里面关于线程状态的注释,这样才能学到一手的知识,避免走弯路。