1先看一张线程转换图
2从源码角度入手
在Thread源码中有有一个内部枚举类State,其中标注了6中状态,网上也有好多说7种状态。其实是运行状态中细分了运行中和就绪状态(通过yield()方法调用,也可以是没有抢到cpu时间片),其实说6种状态即可,也可细说。
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:刚创建线程还没有运行,此时线程为初始状态(NEW)
2.RUNNABLE:当线程启动(调用start()方法等)后,此线程进入运行中状态(RUNNABLE)
3.BLOCKED:如果线程中存在synchronized锁竞争,并且竞争失败,会导致线程进入阻塞状态(BLOCKED),并且只有synchronize锁竞争才会进入BLOCKED状态,其他锁都不会进入BLOCKED状态
4.WAITING:当线程调用wait()、join()、LockSupport.park() 方法会进入等待状态(WAITING)
5.TIMED_WAITING:当线程中调用了Thread.sleep()、wait(long)、join(long)、LockSupport.parkNanos()、LockSupport.parkUntil()这些方法,会进入到超时等待状态,他们共有特性就是经过一定时间会继续执行程序
6.TERMINATED:终止状态就是指线程执行完毕
这期比较简单,主要是这张图太好了,大家只要记住这张图,遇到的线程状态都可解决。