How to check the number of currently running threads in Java?

后端 未结 5 1296
耶瑟儿~
耶瑟儿~ 2020-12-08 05:47

I\'m looking for a way to see the number of currently running threads

  1. Through Windows first
  2. Programmatically
5条回答
  •  温柔的废话
    2020-12-08 06:08

    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

提交回复
热议问题