ps:java线程状态,很基础的问题,但是却很少人能回答正确。昨天面试,被问到这个问题,按照网上的资料巴拉巴拉的讲了一遍,面试官让我回去的时候再看看源码。今天一看,果然网上70%的文章都是错的。
首先说明,这里说的java线程的状态,指的是JVM的线程状态,不能反映操作系统的线程状态。所以jvm线程状态与操作系统线程状态不是一致的。
Thread的内部枚举类Thread.State定义了java线程的六种线程状态,分别是:NEW,RUNNABLE,RUNNABLE,WAITING,TIMED_WAITING,TERMINATED;
下面我来详细解释一下什么时候会出现各种状态:
- NEW 新建状态
/**
* Thread state for a thread which has not yet started.
*
* 还未调用start方法的时候线程处于这个状态
*/
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.
*
* 表示jvm中正在执行,但是在操作系统中可能处于watting状态。即在操作系统的
* 线程状态可能处于watting状态,也有可能处于running状态。
*/
RUNNABLE,
- 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
* {@link Object#wait() Object.wait}.
*
* 1.想要获取对象的同步锁,但是该同步锁被其他线程占用;
* 2.在调用无参的wait方法之后(notify,notifyAll方法已调用)的状态。
* 简而言之:当因为获取不到锁而无法进入同步块时,线程处于 BLOCKED 状态。
*
* 总结:Blocked是在等待线程获取锁,是被动的阻塞;waiting或者timed_waiting是在等待其它
* 线程发来通知(调用Thread类的notify()/notifyAll()方法),收到通知后就可能进入
* runnable状态或者进入重新获取锁的竞争,如果竞争失败进入Blocked状态。
*/
BLOCKED,
- WAITING 等待状态
/**
* Thread state for a waiting thread.
* A thread is in the waiting state due to calling one of the
* following methods:
* <ul>
* <li>{@link Object#wait() Object.wait} with no timeout</li>
* <li>{@link #join() Thread.join} with no timeout</li>
* <li>{@link LockSupport#park() LockSupport.park}</li>
* </ul>
*
* <p>A thread in the waiting state is waiting for another thread to
* perform a particular action.
*
* For example, a thread that has called <tt>Object.wait()</tt>
* on an object is waiting for another thread to call
* <tt>Object.notify()</tt> or <tt>Object.notifyAll()</tt> on
* that object. A thread that has called <tt>Thread.join()</tt>
* is waiting for a specified thread to terminate.
*
* 1.调用无参的wait方法,等待另一个线程调用对象的notify,notifyAll;
* 2.调用无参的join方法,等待另一个线程执行结束;
* 3.调用LockSupport.park方法;
*/
WAITING,
- 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:
* <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>
*
* 1.调用Sleep方法后;
* 2.调用有参的wait方法后;
* 3.调用有参的join方法后;
* 4.调用LockSupport.parkNanos和LockSupport.parkUntil方法;
*/
TIMED_WAITING,
- TERMINATED 终止状态
/**
* Thread state for a terminated thread.
* The thread has completed execution.
* 线程已经执行完成,或者发生异常,或者调用Thread.stop方法
*/
TERMINATED;
附图:
JVM层面与OS层面线程状态的关系