线程的状态有几种?
程序员文章站
2022-05-05 16:35:02
...
一、Java中的状态类
看一下State类,该类为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;
}
二、六种状态解析
可以看出一共由六种状态
1.New:新建状态 新建Thread没有调用start
2.Runnable:可运行状态,包含就绪和运行
3.Blocked:阻塞状态,线程请求资源失败会进入该状态,所有阻塞线程都会存在一个阻塞队列中,阻塞线程会不断请求资源请求成功后会进入就绪队列,等待执行
4.Waiting:等待状态,等待状态线程主动放弃CPU执行权,例如wait,join等方法就会进入该状态,同样有一个等待队列存储所有等待线程,线程等待其他线程唤醒才能继续执行
5.Timed_Waiting计时等待:也是主动放弃CPU执行权的,区别是,超时后会结束等待状态
6.Terminal:结束状态 线程结束后的状态
三、状态转换图