Home >Java >javaTutorial >How Can I Programmatically List All Running Threads in a Java Program?
Java provides a built-in mechanism to list all active threads within the Java Virtual Machine (JVM). This includes threads created by the current class and those initiated by external processes.
To retrieve an iterable set of all running threads, utilize the following code:
Set<Thread> threadSet = Thread.getAllStackTraces().keySet();
This approach offers a lightweight performance overhead, typically consuming a negligible amount of time for a reasonable number of threads (e.g., 0 ms for 12 threads in an Azul JVM 16.0.1 environment running on Windows 10).
Additionally, it is possible to extract the Thread and Class objects associated with each thread in the list:
for (Thread thread : threadSet) { String threadName = thread.getName(); Class<?> threadClass = thread.getClass(); }
This allows you to inspect thread properties and class information, such as the thread's name and the Java class that created it.
The above is the detailed content of How Can I Programmatically List All Running Threads in a Java Program?. For more information, please follow other related articles on the PHP Chinese website!