I\'m looking for a way to see the number of currently running threads
Code snippet:
import java.util.Set;
import java.lang.Thread.State;
public class ActiveThreads {
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 threadSet = Thread.getAllStackTraces().keySet();
for ( Thread t : threadSet){
if ( t.getThreadGroup() == Thread.currentThread().getThreadGroup() &&
t.getState() == Thread.State.RUNNABLE){
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();
}
}
}
output:
Thread :Thread[main,5,main]:state:RUNNABLE
Thread count started by Main thread:1
Explanation:
Thread.getAllStackTraces().keySet()
provides you list of all Threads, which have been started by both Program and System
. In absence of ThreadeGroup
condition, you will get System thread count if they are active.
Reference Handler, Signal Dispatcher,Attach Listener and Finalizer