java线程的生命周期与状态
根据Sun官方的说法:
A thread can be in one of the five states. According to sun, there is only 4 states in thread life cycle in java new, runnable, non-runnable and terminated. There is no running state.sun的说法是线程有四个状态,新,可运行,不可运行,以及终止状态
但是为了更好地理解线程,我们也可以以5种状态下进行了解释。
- New
- Runnable
- Blocked
- Waiting
- Timed Waiting
- Terminated
新线程状态(New Thread)
刚创建的新线程,它处于新状态。 当线程处于此状态时,该线程尚未开始运行。
The thread is in new state if you create an instance of Thread class but before the invocation of start() method.
可运行状态(Runnable ):
准备运行的线程移至可运行状态。 在这种状态下,线程可能实际上正在运行,或者在任何时候都可以运行。 线程调度程序负责给线程运行时间。
多线程程序为每个单独的线程分配固定的时间量。 每个线程都会运行一会儿,然后暂停并将CPU放弃给另一个线程,以便其他线程有机会运行。 发生这种情况时,所有准备运行,等待CPU和当前运行的线程的线程都处于可运行状态。
调用start()方法后,线程处于可运行状态,但是线程调度程序未将其选择为正在运行的线程。
The thread is in runnable state after invocation of start() method, but the thread scheduler has not selected it to be the running thread.
正在运行状态(Runing):
如果线程调度程序选择了该线程,则该线程处于运行状态。
The thread is in running state if the thread scheduler has selected it.
阻止/等待状态(Blocked/Waiting)(也可以叫做不可运行状态):
线程暂时处于非活动状态时,处于以下状态之一:
受阻
等候
For example, when a thread is waiting for I/O to complete, it lies in the blocked state. It’s the responsibility of the thread scheduler to reactivate and schedule a blocked/waiting thread. A thread in this state cannot continue its execution any further until it is moved to runnable state. Any thread in these states does not consume any CPU cycle.
A thread is in the blocked state when it tries to access a protected section of code that is currently locked by some other thread. When the protected section is unlocked, the schedule picks one of the thread which is blocked for that section and moves it to the runnable state. Whereas, a thread is in the waiting state when it waits for another thread on a condition. When this condition is fulfilled, the scheduler is notified and the waiting thread is moved to runnable state.
If a currently running thread is moved to blocked/waiting state, another thread in the runnable state is scheduled by the thread scheduler to run. It is the responsibility of thread scheduler to determine which thread to run.
这是线程仍处于活动状态但当前不符合运行条件的状态。
This is the state when the thread is still alive, but is currently not eligible to run.
定时等待状态(Timed Wating,这也是属于不可运行状态下的一个细分状态):
Timed Waiting: A thread lies in timed waiting state when it calls a method with a time out parameter. A thread lies in this state until the timeout is completed or until a notification is received. For example, when a thread calls sleep or a conditional wait, it is moved to a timed waiting state.
当线程调用带有超时参数的方法时,线程处于定时等待状态。 线程处于这种状态,直到超时完成或收到通知为止。 例如,当线程调用睡眠或有条件的等待时,它将移至定时等待状态。
终止状态(Terminated):
线程由于以下原因之一而终止:
- 当线程代码完全由程序执行完成时,会终止线程。
- 发生了一些异常错误事件会终止线程
- 处于终止状态的线程不再消耗任何CPU资源
当线程的run()方法退出时,该线程处于终止状态或死状态。
A thread is in terminated or dead state when its run() method exits.