线程的生命周期及各种状态的转换
写在前面
- 很多地方说线程有五种状态我觉得有些笼统,在Thread类的源码中明确描述了线程共有六种状态,分别是:NEW、RUNNABLE、BLOCKED、WAITING、TIME_WAITING、TERMINATED
线程六种状态详解
- NEW:初始状态,线程被创建,但是还没有调用start方法
- RUNNABLE:运行状态,Java线程把操作系统中的就绪和运行两种状态统一为“运行中”(操作系统中就绪和运行两种状态的区别是该线程有没有获取到时间片)。
- BLOCKED:阻塞状态
- 线程等待 synchronized 的隐式锁。
- WAITING:等待状态:
- 获得 synchronized 隐式锁的线程,调用无参数的Object.wait()方法
- 调用无参数Thread.join()方法
- 调用LockSupport.park()方法,线程阻塞切换到WAITING状态,
- 调用LockSupport.unpark()方法,可唤醒线程,从WAITING状态切换到RUNNING状态
- TIMED_WAITING:超时等待状态:
- 调用带超时参数的 Thread…sleep(long millis)方法
- 获得 synchronized 隐式锁的线程,调用带超时参数的Object.wait(long timeout)方法
- 调用带超时参数的Thread.join(long millis)方法
- 调用带超时参数的LockSupport.parkNanos(Object blocker,long deadline)方法
- 调用带超时参数的LockSupport.parkUntil(long deadline)方法
- TERMINATED:终止状态,表示当前线程执行完毕。
图解线程六种状态间的转换
源码分析线程的六种状态
入Thread类中的源码
public enum State {
/**
* Thread state for a thread which has not yet started.
*/
NEW,
/**
* 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.
*/
RUNNABLE,
/**
* 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}.
*/
BLOCKED,
/**
* 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.
*/
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>
*/
TIMED_WAITING,
/**
* Thread state for a terminated thread.
* The thread has completed execution.
*/
TERMINATED;
}