线程的状态
关于线程的状态,又说6种状态,又说7种状态,原因是在JDK5之后,Ready和Running合称Runnable状态。

- New 初始状态 :在新建一个thread对象后,线程刚刚建立时
- Ready就绪状态 : 在线程调用start方法后,线程随时准备抢占时间片
- Running 运行状态 :在线程获取到cpu的时间片后,线程正在占用cpu资源
- Time Waiting 限期等待状态 :在线程调用sleep方法后,此线程进入休眠,在一定时间(sleep设定的时间)内,此线程处于限期等待
- Waiting 无限期等待 : 在一个线程one对象调用join后,one所在的线程 进入无限期等待,直到one运行完后,才参与抢占时间片
- Blocked 阻塞状态 : 在一个线程拿到锁标记进入同步代码块后,其他线程不能再进入同步代码块,进入阻塞,直到锁标记释放。
- Terminated 终止状态(消亡状态):在一个线程run内的语句全部结束后,线程终止。
原码
在Thread$State中,有一个枚举类型State,内写明了有6种线程状态。
在Trhead中,有getState()方法,内容如下:
public State getState() {
// get current thread state
return sun.misc.VM.toThreadState(threadStatus);
}
返回线程的运行状态,在eclipse中 按ctrl+左键,进入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;
}
本文详细介绍了线程的六种状态,包括初始状态、就绪状态、运行状态、阻塞状态、等待状态及终止状态,并解释了每种状态的含义及转换条件。
1077

被折叠的 条评论
为什么被折叠?



