Get status of all threads started by your program excluding system threads

suggest change

Code snippet:

import java.util.Set;

public class ThreadStatus {
    public static void main(String args[]) throws Exception {
        for (int i = 0; i < 5; i++){
            Thread t = new Thread(new MyThread());
            t.setName("MyThread:" + i);
            t.start();
        }
        int threadCount = 0;
        Set<Thread> threadSet = Thread.getAllStackTraces().keySet();
        for (Thread t : threadSet) {
            if (t.getThreadGroup() == Thread.currentThread().getThreadGroup()) {
                System.out.println("Thread :" + t + ":" + "state:" + t.getState());
                ++threadCount;
            }
        }
        System.out.println("Thread count started by Main thread:" + threadCount);
    }
}

class MyThread implements Runnable {
    public void run() {
        try {
            Thread.sleep(2000);
        } catch(Exception err) {
            err.printStackTrace();
        }
    }
}
Thread :Thread[MyThread:1,5,main]:state:TIMED_WAITING
Thread :Thread[MyThread:3,5,main]:state:TIMED_WAITING
Thread :Thread[main,5,main]:state:RUNNABLE
Thread :Thread[MyThread:4,5,main]:state:TIMED_WAITING
Thread :Thread[MyThread:0,5,main]:state:TIMED_WAITING
Thread :Thread[MyThread:2,5,main]:state:TIMED_WAITING
Thread count started by Main thread:6

Explanation:

Thread.getAllStackTraces().keySet() returns live application threads and JVM threads. The comparison keeps threads in the main thread's ThreadGroup. That includes main itself, which is why the count is 6 rather than 5. It does not include every thread the program started if one was placed in another group, and getThreadGroup() is null for a thread that has already died.

Without that check, HotSpot also reports threads such as these. The set depends on the JVM, and Attach Listener appears only after something attaches:

Reference Handler
Signal Dispatcher
Attach Listener
Finalizer

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents