SoFunction
Updated on 2025-04-13

Use Java to view the running status of a thread (with source code)

1. Project background and introduction

In modern Java applications, especially in servers, desktops and real-time monitoring systems involving a large number of concurrent operations, the running status of threads plays a crucial role in troubleshooting problems and optimizing performance. Each thread will undergo different states such as "NEW", "Ready/RUNNABLE", "Blocking", "Waiting", "Timed Waiting" (TIMED_WAITING) and "TERMINATED) in the JVM. Understanding the current state of each thread will help position thread deadlock, resource competition, thread leakage and other problems, and monitor and debug the overall performance of the system.

The goal of this project is to implement a tool to view the running status of threads. This tool uses Java built-in API (such as () method) to obtain information about all threads in the JVM, extracts data such as the name, status, priority, and thread group of each thread, and then outputs it to the console in a formatted manner. With this tool, developers can intuitively understand the running status of each thread in the current system, thereby providing effective support for debugging and optimizing multi-threaded programs.

2. Overview of related knowledge

2.1 Java multithreading basics and threading state

Java's multi-threaded programming allows programs to perform multiple tasks simultaneously. Each thread is represented by a class and has an independent life cycle. Threads may be in the following states during operation:

NEW: The thread object is in a new state when it has not been started after it has been created.

RUNNABLE: The thread has been started and is waiting or running. Note that in Java, the RUNNABLE state contains the situations where the CPU time slice is being run and waiting.

BLOCKED: The thread is blocked while waiting to acquire an object lock (monitor).

WAITING: After the thread actively calls the wait() method, it enters an infinite wait state until it is woken up by other threads.

TIMED_WAITING: The waiting state with time limit entered by a thread after calling sleep(), wait(timeout) or join(timeout) methods.

TERMINATED: The thread's run() method enters a terminated state after execution.

Mastering the concept of thread state helps developers understand thread scheduling and synchronization mechanisms, further improving system performance and stability.

2.2 The importance of thread state

Thread state has the following significance for debugging and performance monitoring:

Debugging Problem: In a multithreaded program, if a thread is always in BLOCKED or WAITING state, it may mean deadlock or resource competition issues. Checking thread status can help developers quickly locate problem threads.

Performance monitoring: By counting the number of threads in different states, you can judge the system load situation. For example, too many threads in the RUNNABLE state may cause CPU overload.

Resource Management: Understanding thread state helps detect thread leakage problems and ensures that there are no unnecessary idle threads in the system to occupy resources.

Therefore, designing a tool to view thread state in real time is very helpful for multi-threaded debugging and system optimization.

2.3 Methods to get thread state in Thread class

The Thread class in Java provides many methods for managing and querying threads, among which:

getState(): Returns the status of the current thread (enumeration type), that is, NEW, RUNNABLE, BLOCKED, WAITING, TIMED_WAITING or TERMINATED.

(): Static method, returning a Map<Thread, StackTraceElement[]> object, which contains information about all threads in the current JVM. By traversing the map, we can not only get the state of the thread, but also get information such as the thread's name, priority, and thread group to which we belong.

This project will mainly use these two methods to obtain and display thread status.

3. Project implementation ideas and architecture design

This project aims to implement a simple tool for viewing the running status of all threads in the JVM. The main implementation ideas of the project are as follows:

1. Get all thread information

Call the () method to obtain a Map object containing all threads and their stack information in the current JVM.

2. Iterate through the thread collection

Iterate over the key collection of Map, call the getState() method for each thread to obtain the current state, and obtain information such as thread name, priority, thread group, etc.

3. Format the output thread status

Use the () method to format the thread information into easy-to-read strings and output it to the console in a certain order. The output results can be sorted using TreeSet for easy viewing and comparison.

4. Exception handling

Consider possible exceptions in the process of obtaining thread information to ensure the robustness of the tool.

The architectural design diagram is as follows:

┌────────────────────────────────────────────┐
│                   Main method entry                           │
│                                            │
│   1. Call () Get    │
│       All thread information in the current JVM
│                                            │
│   2. Traverse the thread Map, call getState() to get the status  │
│       and other basic information
│                                            │
│   3. Format and output thread status to the console                     │
└────────────────────────────────────────────┘

The project adopts a simple and intuitive implementation method, and all code is integrated into a Java class, which is convenient for beginners to understand and subsequent extensions.

4. Project code implementation

The complete code is provided below, all logic is integrated into a Java class, with very detailed comments attached to the code to facilitate readers to understand implementation details line by line.

Complete code (including detailed comments)

import ;
import ;
import ;
 
/**
  * ThreadStateViewer
  *
  * This class is used to demonstrate how to obtain and output the running status information of all threads in the JVM.
  * Features include:
  * 1. Get all threads and their stack information in the current JVM through the () method;
  * 2. Iterate through the thread collection and extract the name, status, priority and thread group of each thread;
  * 3. Format the obtained information and output it to the console to facilitate debugging and monitoring the running status of the thread.
  *
  *How to use:
  * Run the ThreadStateViewer class to view the detailed running status information of all threads in the current JVM in the console.
  */
public class ThreadStateViewer {
 
    /**
      * Main method, program entry.  Responsible for obtaining information about all threads in the current JVM and outputting the running status of each thread.
      *
      * @param args command line arguments (not used)
      */
    public static void main(String[] args) {
        // Get all threads and their stack information in the current JVM through ()        Map&lt;Thread, StackTraceElement[]&gt; threadMap = ();
        
        // To make the output result order, create a TreeSet to sort the thread information (sorted by thread name)        Set&lt;String&gt; threadInfoSet = new TreeSet&lt;&gt;();
 
        // traverse all thread objects of thread Map        for (Thread thread : ()) {
            // Get the thread name            String threadName = ();
            // Get the current state of the thread (NEW, RUNNABLE, BLOCKED, WAITING, TIMED_WAITING, TERMINATED)             state = ();
            // Get thread priority            int priority = ();
            // Get the name of the thread group to which the thread belongs (if the thread group is null, output "N/A")            String groupName = (() != null) ? ().getName() : "N/A";
            // Format the current thread information string            String threadInfo = ("Thread Name: %-20s Status: %-15s Priority: %-2d Thread Group: %s",
                    threadName, state, priority, groupName);
            // Add the formatted thread information to the collection            (threadInfo);
        }
 
        // Output thread list title and divider        ("The current running status of all threads in the JVM:");
        ("---------------------------------------------------------------");
        // traverse the ordered set and output thread information line by line        for (String info : threadInfoSet) {
            (info);
        }
        ("---------------------------------------------------------------");
        // Output the total number of threads        ("Total number of threads:" + ());
    }
}

5. Code interpretation

Function description of each method

main method

Function: As a program entrance, the main method calls the () method to obtain all threads and their stack information in the current JVM. Then, by traversing the acquired thread collection, the name, running status (call the getState() method), priority, and thread group to which each thread is extracted. This information is formatted and stored in a TreeSet, so that the thread information is sorted, and then outputted to the console, and finally output the total number of threads.

Note: This method realizes dynamic viewing of all thread states, and makes the output results clear and intuitive through formatting and sorting, which helps to quickly locate and analyze multi-threaded operation.

6. Project Summary and Expansion

Project Summary

This project shows how to use the built-in Java API to get the running status of all threads in the current JVM and output it in format. The main gains are as follows:

Master the method of obtaining thread state: Through the () and () methods, the basic information and running status of all threads can be dynamically obtained, providing strong support for troubleshooting problems such as deadlocks, performance bottlenecks and thread leakage.

Improve multi-threaded debugging and monitoring capabilities: Format output and sorting display thread information, which helps developers intuitively understand the distribution and running status of each thread in the system, so as to promptly discover abnormal threads or system bottlenecks.

Code specification and readability: Modular design and detailed annotations make the code structure clear, easy to expand and maintain subsequently, and also provides a good reference example for team collaboration.

Expansion direction

In actual projects, the following extensions can be made based on this project:

Graphical display: Develop a graphical interface with Swing or JavaFX, display thread state information in a table or tree structure to achieve real-time refresh and dynamic monitoring.

Detailed stack information display: In addition to basic thread information, it can also expand the stack trace information of each thread to help locate the code segments and potential problems that the thread is executing.

Custom filtering and sorting: Added filtering function, supports threads that only display specific thread groups and specific states (such as BLOCKED or WAITING), and perform multi-dimensional sorting based on priority, status or name.

Log integration and timing monitoring: Integrate thread status information into the log system, timely record thread status changes, providing a basis for long-term performance monitoring and abnormal troubleshooting.

Thread dynamic management: Based on the results of thread state monitoring, automatic warning and management mechanisms are designed, such as automatically sending alarms or recycling resources when a large number of threads are detected in BLOCKED state.

The above is the detailed content of using Java to view the running status of a thread (with source code). For more information about Java to view the running status of a thread, please pay attention to my other related articles!