如何在Java显示所有线程状态?
线程是进程内的轻量级进程Java中的多线程是一个 允许同时执行程序的两个或多个部分以最大化 CPU 利用率的功能。这里检索线程状态的方法是通过 Thread 类的getState()方法。 Java线程可以存在于以下任何一种状态,线程的状态是它在给定实例中存在的状态。如上图所示的线程的生命周期是了解更多状态的最佳途径,其中状态如下:
- 新的
- 可运行
- 被封锁
- 等待
- 定时等待
- 已终止
Note: When a thread is getting executed all other threads are in blocking state and not in waiting state.
过程:显示线程状态
- 线程是通过实现可运行接口来创建的。
- 线程的状态可以通过 Thread 类对象的getState()方法获取。
例子:
Java
// Java Program to Display all Threads Status
// Importing Set class fom java.util package
import java.util.Set;
// Class 1
// helepr Class implementing Runnable interface
class MyThread implements Runnable {
// run() method whenever thread is invoked
public void run()
{
// Try block to check for exceptions
try {
// making thread to
Thread.sleep(2000);
}
// Catch block to handle the exceptions
catch (Exception err) {
// Print the exception
System.out.println(err);
}
}
}
// Class 2
// Main Class to check thread status
public class GFG {
// Main driver method
public static void main(String args[]) throws Exception
{
// Iterating to create multiple threads
// Customly creating 5 threads
for (int thread_num = 0; thread_num < 5;
thread_num++) {
// Creating single thread object
Thread t = new Thread(new MyThread());
// Setting name of the particular thread
// using setName() method
t.setName("MyThread:" + thread_num);
// Starting the current thread
// using start() method
t.start();
}
// Creating set object to hold all the threads where
// Thread.getAllStackTraces().keySet() returns
// all threads including application threads and
// system threads
Set threadSet
= Thread.getAllStackTraces().keySet();
// Now, for loop is used to iterate through the
// threadset
for (Thread t : threadSet) {
// Printing the thread status using getState()
// method
System.out.println("Thread :" + t + ":"
+ "Thread status : "
+ t.getState());
}
}
}
输出: