Java 中的线程生命周期 - Java 中的线程状态

从我们最后的教程,我们可以创建一个( / 社区/教程/java-thread-example Java Thread Example – Extending Thread Class and Implementing Runnable Interface)类通过实施可运行界面或通过扩展 Thread 类,但要启动一个 Java 线程,我们首先必须创建一个 Thread 对象,并将其称为 start() 方法来执行 run() 方法作为一个线程。

Java 中的生命周期

Below diagram shows different states of thread life cycle in java. We can create a thread in java and start it but how the thread states change from Runnable to Running to Blocked depends on the OS implementation of thread scheduler and java doesn't have full control on that. Thread Life cycle in java, Thread States in java, thread life cycle

当我们使用 new 运算器创建一个新的 Thread 对象时, thread 状态是 New Thread. 在此时刻, thread 并不活着,它是 Java 编程的内部状态。

跑步

当我们在 Thread 对象上调用 start() 函数时,其状态被更改为可运行. 控制权交给 Thread Scheduler 以完成其执行。

跑步

当 thread 运行时,其状态会更改为 Running. Thread Scheduler 会从可运行 thread 池中选择一个 thread 并将其状态更改为 Running. 然后 CPU 会开始执行这个 thread. 一个 thread 可以从 Runable、Dead 或 Blocked 状态更改状态,取决于时间切割、 thread 完成 run() 方法或等待一些资源。

封锁 / 等待

一个线程可以等待其他线程使用 线程加入完成,或者它可以等待一些资源可用。例如 生产者消费者问题waiter notifier implementation或 IO 资源,然后将其状态更改为等待。

死者

一旦线程完成执行,它的状态被更改为死,并且被认为不是活的. 上面是不同的 ** states of thread**. 了解它们以及线程如何改变它的状态是很好的。

Published At
Categories with 技术
Tagged with
comments powered by Disqus