Get a list of all threads currently running in Java

后端 未结 13 1475
[愿得一人]
[愿得一人] 2020-11-22 02:30

Is there any way I can get a list of all running threads in the current JVM (including the threads not started by my class)?

Is it also possible to get the

相关标签:
13条回答
  • 2020-11-22 03:09

    In Groovy you can call private methods

    // Get a snapshot of the list of all threads 
    Thread[] threads = Thread.getThreads()
    

    In Java, you can invoke that method using reflection provided that security manager allows it.

    0 讨论(0)
  • 2020-11-22 03:10

    Get a handle to the root ThreadGroup, like this:

    ThreadGroup rootGroup = Thread.currentThread().getThreadGroup();
    ThreadGroup parentGroup;
    while ((parentGroup = rootGroup.getParent()) != null) {
        rootGroup = parentGroup;
    }
    

    Now, call the enumerate() function on the root group repeatedly. The second argument lets you get all threads, recursively:

    Thread[] threads = new Thread[rootGroup.activeCount()];
    while (rootGroup.enumerate(threads, true ) == threads.length) {
        threads = new Thread[threads.length * 2];
    }
    

    Note how we call enumerate() repeatedly until the array is large enough to contain all entries.

    0 讨论(0)
  • 2020-11-22 03:10

    Have you taken a look at jconsole?

    This will list all threads running for a particular Java process.

    You can start jconsole from the JDK bin folder.

    You can also get a full stack trace for all threads by hitting Ctrl+Break in Windows or by sending kill pid --QUIT in Linux.

    0 讨论(0)
  • 2020-11-22 03:11

    Apache Commons users can use ThreadUtils. The current implementation uses the walk the thread group approach previously outlined.

    for (Thread t : ThreadUtils.getAllThreads()) {
          System.out.println(t.getName() + ", " + t.isDaemon());
    }
    
    0 讨论(0)
  • 2020-11-22 03:11

    To get a list of threads and their full states using the terminal, you can use the command below:

    jstack -l <PID>
    

    Which <PID> is the id of process running on your computer. To get the process id of your java process you can simply run the jps command.

    Also, you can analyze your thread dump that produced by jstack in TDAs (Thread Dump Analyzer) such fastthread or spotify thread analyzer tool.

    0 讨论(0)
  • 2020-11-22 03:12

    To get an iterable set:

    Set<Thread> threadSet = Thread.getAllStackTraces().keySet();
    
    0 讨论(0)
提交回复
热议问题