- @since1.5
* @see #getState
*/
public enum State {
/**
* Thread state for a thread which has not yet started.
* 此时还没有调用start方法,实际上并没有创建线程
*/
NEW,
/**
* Thread state for a runnable thread. A thread inthe runnable
* state is executing inthe Java virtual machine butit may
* be waiting for other resources fromthe operating system
* such as processor.
* start()结束后,变为次状态,可以理解为存活着正尝试争用CPU的线程
* 如运行中的线程发生yield()让步操作,线程还是runnable状态,但是它并没有占用CPU了
*/
RUNNABLE,
/**
* Thread state for a thread blocked waiting for a monitor lock.
* A thread inthe 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}.
* 阻塞状态,或者说挂起,原因通常是在等待一个锁,当synchronized正好有线程在使用时,一个线程尝试进入这个临界区就会被阻塞,知道另一个线程走完临界区或者发生了相应锁对象的wait操作后,才有进入的权利恢复到runnable
* interrupt()也不能唤醒阻塞的线程,只是做了唤醒动作的标记而已,isInterrupt()可以获得结果,
* 1.6版本后interrupted()也可以获得结果,不同的是这个方法调用后会将标记重置为false
*/
BLOCKED,
/**
* Thread state for a waiting thread.
* A thread isinthe waiting state due to calling one ofthe
* 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 inthe 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.
* 通常是线程拥有对象锁进入相应代码区后,调用对应锁对象的wait()产生的后果,变相的实现还有LockSupport.park(),Thread.join()等,他们也是在等待另一个对象时间的发生。经典例子就是 消费者和生产者。对锁对象做了notify()动作将从等待池唤醒一个线程恢复到runnable,notifyAll()唤醒全部线程。
* 在这种情况下和TIMED_WAITING调用interrupt()是有用的,线程内部会抛出interrupt异常,应当在run方法中捕获做对应处理。
*/
WAITING,
/**
* Thread state for a waiting thread with a specified waiting time.
* A thread isinthe 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>
* Object.wait()有两个重构方法,可设置时间,此时状态为TIMED_WAITING
* Thread.sleep(),LockSupport.park()等的重构方法也可以达到这样的状态
*/
TIMED_WAITING,
/**
* Thread state for a terminated thread.
* The thread has completed execution.
* run()方法走完,此时线程可能已经被操作系统注销,这个状态只是JAVA的状态
*/
TERMINATED;
}
/**
* The minimum priority that a thread can have.
*/publicfinalstaticint MIN_PRIORITY = 1;
/**
* The default priority that is assigned to a thread.
*/publicfinalstaticint NORM_PRIORITY = 5;
/**
* The maximum priority that a thread can have.
*/publicfinalstaticint MAX_PRIORITY = 10;