File tree Expand file tree Collapse file tree 1 file changed +5
-1
lines changed Expand file tree Collapse file tree 1 file changed +5
-1
lines changed Original file line number Diff line number Diff line change @@ -147,12 +147,16 @@ Java 线程在运行的生命周期中的指定时刻只可能处于下面 6 种
147
147
148
148
由上图可以看出:线程创建之后它将处于 ** NEW(新建)** 状态,调用 ` start() ` 方法后开始运行,线程这时候处于 ** READY(可运行)** 状态。可运行状态的线程获得了 CPU 时间片(timeslice)后就处于 ** RUNNING(运行)** 状态。
149
149
150
- > 操作系统隐藏 Java 虚拟机(JVM)中的 READY 和 RUNNING 状态,它只能看到 RUNNABLE 状态(图源:[ HowToDoInJava] ( https://howtodoinJava.com/ " HowToDoInJava ") :[ Java Thread Life Cycle and Thread States] ( https://howtodoinJava.com/Java/multi-threading/Java-thread-life-cycle-and-thread-states/ " Java Thread Life Cycle and Thread States ") ),所以 Java 系统一般将这两个状态统称为 ** RUNNABLE(运行中)** 状态 。
150
+ > 在操作系统中层面线程有 READY 和 RUNNING 状态,而在 JVM 层面只能看到 RUNNABLE 状态(图源:[ HowToDoInJava] ( https://howtodoinJava.com/ " HowToDoInJava ") :[ Java Thread Life Cycle and Thread States] ( https://howtodoinJava.com/Java/multi-threading/Java-thread-life-cycle-and-thread-states/ " Java Thread Life Cycle and Thread States ") ),所以 Java 系统一般将这两个状态统称为 ** RUNNABLE(运行中)** 状态 。
151
+ >
152
+ > ** 为什么 JVM 没有区分这两种状态呢?** (摘自:[ java线程运行怎么有第六种状态? - Dawell的回答] ( https://www.zhihu.com/question/56494969/answer/154053599 ) ) 现在的<b >时分</b >(time-sharing)<b >多任务</b >(multi-task)操作系统架构通常都是用所谓的“<b >时间分片</b >(time quantum or time slice)”方式进行<b >抢占式</b >(preemptive)轮转调度(round-robin式)。这个时间分片通常是很小的,一个线程一次最多只能在 CPU 上运行比如 10-20ms 的时间(此时处于 running 状态),也即大概只有 0.01 秒这一量级,时间片用后就要被切换下来放入调度队列的末尾等待再次调度。(也即回到 ready 状态)。线程切换的如此之快,区分这两种状态就没什么意义了。
151
153
152
154
![ RUNNABLE-VS-RUNNING] ( https://my-blog-to-use.oss-cn-beijing.aliyuncs.com/2019-3/RUNNABLE-VS-RUNNING.png )
153
155
154
156
当线程执行 ` wait() ` 方法之后,线程进入 ** WAITING(等待)** 状态。进入等待状态的线程需要依靠其他线程的通知才能够返回到运行状态,而 ** TIME_WAITING(超时等待)** 状态相当于在等待状态的基础上增加了超时限制,比如通过 ` sleep(long millis) ` 方法或 ` wait(long millis) ` 方法可以将 Java 线程置于 TIMED WAITING 状态。当超时时间到达后 Java 线程将会返回到 RUNNABLE 状态。当线程调用同步方法时,在没有获取到锁的情况下,线程将会进入到 ** BLOCKED(阻塞)** 状态。线程在执行 Runnable 的` run() ` 方法之后将会进入到 ** TERMINATED(终止)** 状态。
155
157
158
+ 相关阅读:[ 挑错 |《Java 并发编程的艺术》中关于线程状态的三处错误] ( https://mp.weixin.qq.com/s/UOrXql_LhOD8dhTq_EPI0w ) 。
159
+
156
160
## 7. 什么是上下文切换?
157
161
158
162
线程在执行过程中会有自己的运行条件和状态(也称上下文),比如上文所说到过的程序计数器,栈信息等。当出现如下情况的时候,线程会从占用 CPU 状态中退出。
You can’t perform that action at this time.
0 commit comments