了解在使用线程和为多线程环境编程时,理解Java中的线程生命周期和线程状态非常重要。从我们上一篇教程中,我们可以通过实现Runnable接口或通过扩展Thread类来创建Java线程类,但要启动一个Java线程,我们首先必须创建Thread对象并调用其start()方法以执行run()方法作为线程。
Java线程的生命周期
下图显示了Java线程生命周期的不同状态。我们可以在Java中创建并启动一个线程,但线程状态如何从Runnable更改为Running再到Blocked取决于线程调度程序的操作系统实现,而Java对此没有完全控制。
新建
当我们使用new操作符创建一个新的Thread对象时,线程的状态是New Thread。在这一点上,线程还没有启动,它是Java编程中的一个内部状态。
Runnable
当我们在Thread对象上调用start()函数时,它的状态会改变为Runnable。控制权被交给线程调度程序来完成其执行。是立即运行这个线程还是在运行之前将其放入可运行的线程池中,取决于线程调度程序的操作系统实现。
Running
当线程正在执行时,它的状态会变为Running。线程调度程序从可运行的线程池中选择一个线程,并将其状态更改为Running。然后CPU开始执行此线程。线程可以根据时间片分配、run()方法的完成或等待某些资源而将状态更改为Runnable、Dead或Blocked。
Blocked/Waiting
A thread can be waiting for other thread to finish using thread join or it can be waiting for some resources to available. For example producer consumer problem or waiter notifier implementation or IO resources, then it’s state is changed to Waiting. Once the thread wait state is over, it’s state is changed to Runnable and it’s moved back to runnable thread pool.
Dead
一旦线程执行完成,其状态将被更改为Dead,并被视为不再存活。以上是线程不同状态的描述。了解这些状态以及线程如何更改其状态是很重要的。这就是Java中线程生命周期的全部内容。
Source:
https://www.digitalocean.com/community/tutorials/thread-life-cycle-in-java-thread-states-in-java