您的位置:首页 > 编程语言 > Java开发

java8中线程的状态

2016-05-09 18:48 429 查看
java8中获取线程状态的方法是Thread.getState(),返回的是一个enum类型,具体定义如下:

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个状态,下面是对这6个状态转换的简单总结。

1,NEW,Thread对象已经new出来了,还没有调用start方法。

2,RUNNABLE 调用了start()方法,线程进入可运行态,这里java没有区分线程正在执行还是在等待分配cpu时间片而在等待,统一被归为 RUNNABLE。

3,BLOCKED 阻塞态,通常与锁有关系,线程在等待持有一把锁相关的资源,比如进入同步块,获取ReentryLock等。

4,WAITING 等待状态,线程在等待另外一个线程来唤醒自己。比如另外的线程调用notify, notifyAll, 或者另外的线程终止(join方法会等待此条件)。

5,TIMED_WAITING 定时的等待,是对WAITING的一种细化,WAITING是无限期等待,而这里只会等待有限的时间。

6,TERMINATED 线程执行完任务,终止了。

从概念上来说,4、5两种状态可以合并来看,所以最终有5个不同的线程状态。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: