线程一共有六种状态:
NEW, RUNNABLE, BLOCKED, WAITING, TIMED_WAITING, 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;
}
NEW:在线程执行start方法之前的状态。
RUNNABLE:执行start方法后,变为这个状态,可能正在运行也可能处理就绪状态(线程已经准备好执行,但是CPU的执行权限还没有给他)。
BLOCKED:阻塞状态,当线程执行同步方法或者同步代码块时,如果没有获取到对象锁,那么线程就是阻塞状态。
WAITING:等待状态,当线程执行Object.wait(), Thread.join(), 方法时,会变为等待状态, 等执行Object.notify(), Object.notifyAll()时,会将线程唤醒,进入RUNNABLE状态。
TIMED_WAITING超时等待状态,当线程执行Thread.sleep(long millis), Object.wait(long millis), Thread.join(long millis)方法时会进入超时等待状态。等时间到了之后,会自动唤醒。
TERMINATED终止状态,等线程执行完毕,就变为了这个状态