Java Thread How to - Get Active threads in ExecutorService








Question

We would like to know how to get Active threads in ExecutorService.

Answer

//from  w ww  .ja  v  a2s . com
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;

public class Main {
  public static void main(String[] args) {
    final ThreadGroup threadGroup = new ThreadGroup("workers");
    ExecutorService executor = Executors
        .newCachedThreadPool(new ThreadFactory() {
          public Thread newThread(Runnable r) {
            return new Thread(threadGroup, r);
          }
        });
    System.out.println(threadGroup.activeCount());
  }
}

The code above generates the following result.