2017  Kodetalk | Feedback | Privacy Policy | Terms | About
userimage

How to get number of live current threads running in using java code?

How to get number of live current threads running in using java code? Need a complete example for reference.

userimage

Try below code for getting total live thread with number of demon and non-demon thread counts.

import java.lang.management.ManagementFactory;
import java.lang.management.ThreadMXBean;

public class LiveThreadExample {

   public static void main(String[] args) {
      //
      // Will get the managed bean for the thread system of the Java
      // virtual machine.
      //
      ThreadMXBean bean = ManagementFactory.getThreadMXBean();

      //
      // Will get both daemon and non-daemon threads.
      //
      int threadCount = bean.getThreadCount();
      System.out.println("Thread Count = " + threadCount + " : Demon Thread : " + bean.getDaemonThreadCount()
            + " : Non demon thread : " + (threadCount - bean.getDaemonThreadCount()));
   }
}
Answer is