views:

254

answers:

5

How can i see the number of threads in a java?

+8  A: 

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.

MarkPowell
+10  A: 
java.lang.Thread.activeCount()

It will return the number of active threads in the current thread's thread group.

docs: http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Thread.html#activeCount()

The MYYN
+9  A: 

Useful tool for debugging java programs, it gives the number of threads and other relevant info on them:

jconsole <process-id>

laura
The other methods are good too, but this is more useful.
ndemir
Nice :). I did not know about this, but this looks really useful.
Alfred
A: 
    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]);
   }

 }

}
Upul
+3  A: 

ManagementFactory.getThreadMXBean().getThreadCount() doesn't limit itself to thread groups as Thread.activeCount() does.

gustafc