原创:转载需注明原创地址 https://www.cnblogs.com/fanerwei222/p/11867086.html
Java 线程状态介绍:
Java官方文档中对Java线程的几种状态做了说明, 说明如下;
public static enum Thread.State extends Enum<Thread.State> A thread state. A thread can be in one of the following states: NEW A thread that has not yet started is in this state. RUNNABLE A thread executing in the Java virtual machine is in this state. BLOCKED A thread that is blocked waiting for a monitor lock is in this state. WAITING A thread that is waiting indefinitely for another thread to perform a particular action is in this state. TIMED_WAITING A thread that is waiting for another thread to perform an action for up to a specified waiting time is in this state. TERMINATED A thread that has exited is in this state. A thread can be in only one state at a given point in time. These states are virtual machine states which do not reflect any operating system thread states.
以这个文档来进行一点说明:
Java 线程共有6个状态:
新建(NEW)
可运行(RUNNABLE)
阻塞(BLOCKED)
等待(WAITING)
超时等待(TIMED_WAITING)
终止(TERMINATED)
各个状态的生成时机和介绍:
1. 新建(NEW)
new Thread() --> 新建
2. 可运行(RUNNABLE)
2.1 就绪 Thread.start() --> 开始线程 --> 到达可运行仓库的门口排队就绪 Object.notify() --> 从等待/超时等待状态回到就绪队列 Object.notifyAll() --> 从等待/超时等待状态回到就绪队列 LockSupport.unpark(Thread) --> 从等待/超时等待状态回到就绪队列 Thread.yield() --> 从运行状态回到就绪队列 获取到 synchronized(Object)块/方法 中的对象锁 --> 从阻塞状态回到就绪队列 2.2 运行 就绪中的线程等待系统调度(得到CPU)成功之后 --> 开始运行 --> 运行中(占用CPU, 占用锁)
3. 阻塞(BLOCKED)
等待获取 synchronized(Object)块/方法 中的对象锁时 --> 阻塞 Thread.sleep(long timeout) --> 从运行状态进入阻塞状态(释放CPU, 占用锁)
4. 等待(WAITING)
Object.wait() --> 从运行状态进入等待状态(释放CPU, 释放锁) Thread.join() --> 从运行状态进入等待状态 LockSupport.park() --> 从运行状态进入等待状态
5. 超时等待(TIMED_WAITING)
Object.wait(long timeout) --> 从运行状态进入超时等待状态(释放CPU, 释放锁) Thread.sleep(long timeout) --> 从运行状态进入超时等待状态(释放CPU, 占用锁) Thread.join(long timeout) --> 从运行状态进入超时等待状态 LockSupport.parkNanos(long timeout) --> 从运行状态进入超时等待状态 LockSupport.parkUntil(long timeout) --> 从运行状态进入超时等待状态
6. 终止(TERMINATED)
Thread.run()执行完毕之后 --> 终止
线程中断说明: interrupt()
线程在等待状态或者阻塞状态, 调用了线程的 interrupt() 方法, 会有以下3个过程: 1. 中断标记会立刻被标记为 true; 2. 随后由于是阻塞状态, 中断标记 true 会被清除 --> 所以又变成了false; 3. 最后抛出 InterruptedException 异常.