文章目录
在Java中,线程有以下六种状态:
- NEW:新建状态,表示线程对象已经被创建但还未启动。
- RUNNABLE:可运行状态,表示线程处于就绪状态,等待系统分配CPU资源执行。
- BLOCKED:阻塞状态,表示线程被挂起,暂时无法执行,可能是在等待某个资源(如I/O操作、获取锁)的过程中。
- WAITING:等待状态,表示线程正在等待另一个线程执行特定操作。
- TIMED_WAITING:计时等待状态,表示线程在等待特定时间内执行某个操作。
- TERMINATED:终止状态,表示线程已经执行完任务或者因异常而结束。
这些状态构成了线程的生命周期,在不同的状态间切换,线程会执行不同的行为和任务。理解线程的状态对于编写多线程程序非常重要,可以帮助你控制线程的行为和逻辑。
在 java.lang.Thread.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种状态是不包含运行状态的.