我们打开Thread类的源码,搜索State字段,会看到State的枚举值
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;
}
从源码了解到线程有6个状态
NEW(新建)
创建后尚未启动的线程的状态(创建之后还未调用start方法)
RUNNABLE(运行)
调用start的方法之后,线程进入RUNNABLE状态
RUNNABLE即允许状态, RUNNABLE包含Running和Ready
处于Running状态的线程位于可运行线程之中,等待被线程调度选中, 获取CPU的使用权
处于Ready状态的线程位于线程池中,等待被线程调度选中,获取CPU的使用权。而处于Ready状态的线程在获得CPU时间后,就变为Running状态的线程
WAITING(无限等待)
处于WAITING状态的线程不会被分配CPU执行时间,需要被其他线程唤醒
以下几种方法会让线程处于无限期的等待状态
没有设置Timeout参数的Object.wait()方法
没有设置Timeout参数的Thread.join()方法
LockSupport.park()方法
TIMED_WAITING(限期等待)
在一定时间后由系统自动唤醒
以下方法会让线程进入限期等待
Thread.sleep()方法
设置了Timeout参数的Object.wait()方法
设置了Timeout参数的Thread.join()方法
LockSupport.partNanos()方法
LockSupport.parkUntil()方法
BLOCKED(阻塞)
等待获取排它锁
线程被阻塞了,阻塞状态与等待状态的区别是,阻塞状态在等待着获取到一个排它锁,这个事件将向另外一个线程放弃这个锁的时候发生,而等待状态一般时间或者有唤醒动作的时候发生,在程序进入同步区域的时候,线程将进入BLOCKED状态。比如说某个线程进入synchronized关键字修饰的方法或者代码块的时候,即获取锁去执行的时候,其他想进入此方法或者代码块的线程只能等待
TERMINATED(结束)
已终止线程的状态, 线程已经结束执行