threads thread practice example java multithreading concurrency

java - thread - Hilos activos en ExecutorService



thread implementation in java (6)

¿Alguna idea de cómo determinar la cantidad de hilos activos que se ejecutan en ExecutorService?


Coloque un contador volátil estático en el hilo que se actualiza siempre que el hilo se active y desactive. Además, mira la API.


Compruebe el código fuente para Executors.newFixedThreadPool ():

return new ThreadPoolExecutor(nThreads, nThreads, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>());

ThreadPoolExecutor tiene un método getActiveCount (). Por lo tanto, puede enviar el ExecutorService a ThreadPoolExecutor o utilizar el código anterior directamente para obtener uno. A continuación, puede invocar getActiveCount ().


La interfaz ExecutorService no define un método para examinar el número de subprocesos de trabajo en el grupo, ya que este es un detalle de implementación

public int getPoolSize() Returns the current number of threads in the pool.

Está disponible en la clase ThreadPoolExecutor

import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; public class PoolSize { public static void main(String[] args) { ThreadPoolExecutor executor = new ThreadPoolExecutor(10, 20, 60L, TimeUnit.SECONDS, new LinkedBlockingQueue()); System.out.println(executor.getPoolSize()); } }

Pero esto requiere que cree explícitamente el ThreadPoolExecutor, en lugar de utilizar la fábrica de ejecutores que devuelve los objetos ExecutorService. Siempre puedes crear tu propia fábrica que devuelva ThreadPoolExecutors, pero aún te quedará la mala forma de usar el tipo concreto, no su interfaz.

Una posibilidad sería proporcionar su propia ThreadFactory que crea hilos en un grupo de hilos conocido, que luego puede contar

import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ThreadFactory; public class PoolSize2 { 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()); } }


Use una implementación de ThreadPoolExecutor y llame a getActiveCount () sobre ella:

int getActiveCount() // Returns the approximate number of threads that are actively executing tasks.

La interfaz ExecutorService no proporciona un método para eso, depende de la implementación.


Asumir pool es el nombre de la instancia de ExecutorService:

if (pool instanceof ThreadPoolExecutor) { System.out.println( "Pool size is now " + ((ThreadPoolExecutor) pool).getActiveCount() ); }


Tuve el mismo problema, así que creé un Runnable simple para rastrear una instancia de ExecutorService.

import java.util.concurrent.ExecutorService; import java.util.concurrent.ThreadPoolExecutor; public class ExecutorServiceAnalyzer implements Runnable { private final ThreadPoolExecutor threadPoolExecutor; private final int timeDiff; public ExecutorServiceAnalyzer(ExecutorService executorService, int timeDiff) { this.timeDiff = timeDiff; if (executorService instanceof ThreadPoolExecutor) { threadPoolExecutor = (ThreadPoolExecutor) executorService; } else { threadPoolExecutor = null; System.out.println("This executor doesn''t support ThreadPoolExecutor "); } } @Override public void run() { if (threadPoolExecutor != null) { do { System.out.println("#### Thread Report:: Active:" + threadPoolExecutor.getActiveCount() + " Pool: " + threadPoolExecutor.getPoolSize() + " MaxPool: " + threadPoolExecutor.getMaximumPoolSize() + " ####"); try { Thread.sleep(timeDiff); } catch (Exception e) { } } while (threadPoolExecutor.getActiveCount() > 1); System.out.println("##### Terminating as only 1 thread is active ######"); } } }

Simplemente puede usar esto con su ejecutor para obtener estados de ThreadPool

Ex

ExecutorService executorService = Executors.newFixedThreadPool(4); executorService.execute(new ExecutorServiceAnalyzer(executorService, 1000));