线程状态源码:
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;
}
线程的六种状态:
-
新建状态: 线程对象创建了但是没有调用start()方法
-
可运行状态(Runnable)
Running(运行中状态): 被调度器(scheduler)选中,CPU正在执行
Ready(就绪状态): 等待调度器调度
Ready ----> 调度器选中 ----> Running
Running ----> 调度器切换 | Thread.yeild() 方法---> Ready
3.无限等待状态(Waiting):-
Runnable --> wait()方法 | join() 方法 ----> Waiting
Waiting -> notify()方法 | notifyAll() ----> Runnable
-
4. 超时等待状态(Timed_Waiting)
Runnable --> sleep(long millis) | wait(long millis) | join(long millis) ---> Timed_Waiting
Timed_Waiting --> 时间一到 | notify() | notifyAll() --> Runnable
5.Blocked(阻塞)
被监视器锁监视的线程,没有获取同步锁的被阻塞
Runnable ---> 没有获取锁 ----> 阻塞
阻塞 ---> 获取锁对象 ---> Runnable
6.Terminated(终止):
Runnable ----> 任务方法执行完毕|发生异常 ---> Terminated