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

后端 未结 5 1290
耶瑟儿~
耶瑟儿~ 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:07

    In response to your following comment

    In the following piece of code: while(resultSet.next()) { name=resultSet.getString("hName"); MyRunnable worker = new MyRunnable(hName); threadExecutor.execute( worker ); } . My thread pool has size of 10. I need to make sure that my program working correctly with multi-threadings & want to check how many threads are running at a certain moment. How can I do this?

    to another answer, I suggest that you profile your code with JVisualVM and check if your thread pool is working as it should. The reason behind this suggestion is that then you don't have to bother with all the other housekeeping threads that JVM manages. Besides what you want to do is why tools like JVisualVM are made for.

    If you are new to profiling Java programs, JVisualVM lets you see what goes on under the hood while you are running your code. You can see the Heap, GC activity, inspect the threads running/waiting any sample/profile your cpu or memory usage. There are quite a few plugins as well.

    0 讨论(0)
  • 2020-12-08 06:08

    This will give you the total number of threads in your VM :

    int nbThreads =  Thread.getAllStackTraces().keySet().size();
    

    Now, if you want all threads currently executing, you can do that :

    int nbRunning = 0;
    for (Thread t : Thread.getAllStackTraces().keySet()) {
        if (t.getState()==Thread.State.RUNNABLE) nbRunning++;
    }
    

    The possible states are enumerated here: Thread.State javadoc

    If you want to see running threads not programmaticaly but with a Windows tool, you could use Process Explorer.

    0 讨论(0)
  • 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<Thread> 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

    0 讨论(0)
  • 2020-12-08 06:19

    From Windows:

    There's bound to be a performance counter for the process that can tell you that.

    Programmatically:

    There's Thread#activeCount:

    Returns an estimate of the number of active threads in the current thread's thread group and its subgroups. Recursively iterates over all subgroups in the current thread's thread group.

    Or more directly, ThreadGroup#activeCount:

    Returns an estimate of the number of active threads in this thread group and its subgroups.

    and ThreadGroup#getParent:

    Returns the parent of this thread group.

    First, if the parent is not null, the checkAccess method of the parent thread group is called with no arguments; this may result in a security exception.

    All of which seem to suggest something along the lines of:

    int activeThreadTotalEstimate() {
        ThreadGroup group;
        ThreadGroup parent;
    
        group = Thread.currentThread().getThreadGroup();
        while ((parent = group.getParent()) != null) {
            group = parent;
        }
        return group.activeCount();
    }
    
    0 讨论(0)
  • 2020-12-08 06:25

    You can get all the threads and their stack traces running in the JVM uses Thread.getAllStackTraces()

    0 讨论(0)
提交回复
热议问题