Search code examples
javamultithreadingthreadgroup

Confusion regarding ThreadGroup#activeCount()


The documentation for ThreadGroup#activeCount() says : Returns an estimate of the number of active threads in this thread group and its subgroups.
Does that count include threads in sleep , wait and join mode or only those threads which are executing run method?

Thanks.


Solution

  • You can easily try this:

    Thread t1 = new Thread(new Runnable() {
    
        @Override
        public void run() {
            Scanner sc = new Scanner(System.in);
            sc.nextInt();
        }
    });
    Thread t2 = new Thread(new Runnable() {
    
        @Override
        public void run() {
            try {
                Thread.sleep(10000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    });
    t1.start();   // this will be RUNNABLE
    t2.start();   // this will be TIMED_WAITING
    System.out.println(Thread.currentThread().getThreadGroup().activeCount());
    

    Prints 3. Commenting the lines

    t1.start();
    t2.start();
    

    leads to printing 1.