如何获得Java进程中的线程数量

我怎样才能看到一个Java进程中的线程数量?

有用的debuggingJava程序的工具,它给出了线程的数量和其他相关的信息:

jconsole <process-id>

 java.lang.Thread.activeCount() 

它将返回当前线程线程组中活动线程的数量。

docs: http : //docs.oracle.com/javase/7/docs/api/java/lang/Thread.html#activeCount()

ManagementFactory.getThreadMXBean().getThreadCount()不会像Thread.activeCount()那样将自身限制为线程组。

Thread类上有一个静态方法,它将返回由JVM控制的活动线程的数量:

Thread.activeCount()

返回当前线程线程组中活动线程的数量。

此外,如果您希望实时监控它们,则外部debugging器应列出所有活动的线程(并允许您暂停其中任意数量的线程)。

  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]); } } } 

我写了一个程序来迭代所有创build的Threads ,并打印每个Thread getState()

 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(); } } } 

输出:

 java ThreadStatus Thread :Thread[MyThread:0,5,main]:state:TIMED_WAITING Thread :Thread[main,5,main]:state:RUNNABLE Thread :Thread[MyThread:1,5,main]:state:TIMED_WAITING Thread :Thread[MyThread:4,5,main]:state:TIMED_WAITING Thread :Thread[MyThread:2,5,main]:state:TIMED_WAITING Thread :Thread[MyThread:3,5,main]:state:TIMED_WAITING Thread count started by Main thread:6 

如果你删除下面的条件

 if ( t.getThreadGroup() == Thread.currentThread().getThreadGroup()) 

你也将得到下面的输出线程,这些线程已经被系统启动了。

Reference Handler, Signal Dispatcher,Attach Listener and Finalizer

通用的解决scheme,不需要像jconsole一样的GUI(不能在远程terminal上工作),ps适用于非java进程,不需要安装JVM。

ps -o nlwp <pid>

使用Linux Top命令

top -H -p (process id)

你可以通过这个方法获得一个程序的进程ID:

ps aux | grep (your program name)

例如 :

ps aux | grep user.py