How to get the number of threads in a Java process

后端 未结 9 760
无人及你
无人及你 2020-12-07 19:49

How can I see the number of threads in a Java process?

相关标签:
9条回答
  • 2020-12-07 20:36

    There is a static method on the Thread Class that will return the number of active threads controlled by the JVM:

    Thread.activeCount()

    Returns the number of active threads in the current thread's thread group.

    Additionally, external debuggers should list all active threads (and allow you to suspend any number of them) if you wish to monitor them in real-time.

    0 讨论(0)
  • 2020-12-07 20:39

    Generic solution that doesn't require a GUI like jconsole (doesn't work on remote terminals), ps works for non-java processes, doesn't require a JVM installed.

    ps -o nlwp <pid>

    0 讨论(0)
  • 2020-12-07 20:40
        public class MainClass {
    
            public static void main(String args[]) {
    
              Thread t = Thread.currentThread();
              t.setName("My Thread");
    
              t.setPriority(1);
    
              System.out.println("current thread: " + t);
    
              int active = Thread.activeCount();
              System.out.println("currently active threads: " + active);
              Thread all[] = new Thread[active];
              Thread.enumerate(all);
    
              for (int i = 0; i < active; i++) {
                 System.out.println(i + ": " + all[i]);
              }
           }
       }
    
    0 讨论(0)
提交回复
热议问题