从操作系统层面来看,线程通常有以下五种状态,前三种是线程的基本状态。
【运行态】:进程正处在处理机上运行,在单处理机环境下,上最多有一个线程处于运行态。
【就绪态】:进程获得了除处理机(CPU)之外的一切资源,一旦得到处理机(CPU),便可立即运行。系统中处于就绪态的进程可能有多个,通常将它排除一个队列,称为就绪队列。
【阻塞态】:又称 等待态。进程正在等待某一时间而暂停运行。
【创建态】:进程正在被创建,未转到就绪态。
【结束态】:进程正在从系统中消失,可能是正常退出或因其它原因中断退出。
状态转换如下图:
Java中线程一共有6种状态:新建(New),运行(Runnable),无限等待(Watting),限期等待(TImed Waitting),阻塞(Blocked),终止(Terminated)。
新建(New):创建后尚未启动的线程处于这种状态。
运行(Runnable):包括操作系统状态种的Running 和 Ready,也就是处于此状态的线程有可能正在执行,也有可能在等待着操作系统未它分配执行时间。
无限等待(Watting):处于这种状态的线程不会被分配处理器执行时间,它们要等待待其它线程显示唤醒。以下方法会让线程陷入无限期的等待状态:
限期等待(TImed Waitting):处于这种状态的线程也不会被分配处理器执行时间,不过无需等待其它线程显示唤醒,在一定时间之后它们会由系统自动唤醒。以下方法会让线程进入限期等待:
阻塞(Blocked):线程被阻塞了,“阻塞状态” 与 “等待状态” 的区别是 “阻塞状态” 在等待着一个排它锁,这个事件将在另一个线程放弃这个锁的时候发生;而 “等待状态” 则是在等待一段时间,或者唤醒动作的发现。在程序进入同步区域的时候,线程将进入这种状态;
终止(Terminated):已终止线程的线程状态,线程已经结束执行。
这6种状态的转换关系如图:
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:
*
* - {@link Object#wait() Object.wait} with no timeout
* - {@link #join() Thread.join} with no timeout
* - {@link LockSupport#park() LockSupport.park}
*
*
* A 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.
*/
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:
*
* - {@link #sleep Thread.sleep}
* - {@link Object#wait(long) Object.wait} with timeout
* - {@link #join(long) Thread.join} with timeout
* - {@link LockSupport#parkNanos LockSupport.parkNanos}
* - {@link LockSupport#parkUntil LockSupport.parkUntil}
*
*/
TIMED_WAITING,(无限等待)
/**
* Thread state for a terminated thread.
* The thread has completed execution.
*/
TERMINATED;(终结)
}