Java Thread Pool Ejecutorservice
1. Piscina de hilo
1.1 ¿En qué circunstancias usas el grupo de subprocesos?
1.2 Beneficios del uso de grupos de subprocesos
2. Ejecutores y ejecutores
2.1 Introducción
EjecutorService es una interfaz que hereda el ejecutor,
Interfaz pública EjecutorService Extender ejecutor {}El ejecutor también es una interfaz, que solo contiene un método:
Ejecutor de interfaz pública {void execute (comando runnable);} La interfaz de nivel superior del grupo de subprocesos en Java es excutor, pero estrictamente hablando >> El exector no es un grupo de subprocesos, sino solo una herramienta para ejecutar hilos. La interfaz real de hilo> grupo es EjecutorService.
3.Executores
Es una clase de fábrica estática, que puede producir diferentes tipos de grupos de hilos, y algunos de los códigos de origen son los siguientes:
Ejecutores de clase pública {// newFixedThreadPoolPublic STACIT EXECTORSORSIVICE NEWFIXEDTHREADPOOL (int nthreads) {return New ThreadPoolExeCutor (nthreads, nthreads, 0l, TimeUnit.MilliseConds, New LinkedBlockqueue <runnable> ());} // NewcachethPool Public Static Staticsececonds StaticsecorsorSorsorSorsorsorsorsorsorSorsors. NewCachedThreadPool () {return New ThreadPoolExecutor (0, Integer.max_value, 60L, TimeUnit.Seconds, New SynChonousqueue <Runnable> ()); } // NewsCheduledThreadPool Public Static ProchuledExecutorService NewsCheduledThreadPool (int corePoolSize) {return New ProchuledThreadPoolExecutor (corepoolSize); } // Newstringooo}Primero veamos un ejemplo específico y usemos ejemplos para ilustrar las similitudes y diferencias entre ellos.
hilo de paquete; import java.util.concurrent.executorservice; import java.util.concurrent.executors; import java.util.concurrent.scheduledexecutorservice;/*** creado por Yang el 16-7-11. */public class ch09_executor {private static void run (ExecutorService ThreadPool) {for (int i = 1; i <5; i ++) {final int taskID = i; threadpool.exeCute (new runnable () {@Override public void run () {for (int i = 1; i <5; i ++) {try {thread.sleep (20);} capt (interruptedException e) {e.PrintStackTRace ();} system.println ("+tarea+" ejecución "de la tarea);}}}}}) ThreadPool.shutdown (); Hilo de un solo hilo. ejecutar (fixthreadpool); // (2) // Run (SinglethreadPool); // (3) // ejecutar (ProchuledThreadPool); // (4)}}4. 4 piscinas de hilos de uso común
4.1 cachedthreadpool
CachedThreadPool creará un área de caché que almacena en caché el hilo inicializado, termina y elimina los hilos que no se han utilizado durante 6 segundos desde el caché.
Si el hilo está disponible, use el hilo que se creó antes. Si el hilo no está disponible, cree un nuevo hilo.
.Reutilizar:
Piscina de tipo caché, primero verifique si hay hilos que se han creado en la piscina. Si hay uno, reutilizado. Si no hay nadie, cree un nuevo hilo y agréguelo a la piscina.
Use escenarios:
Las piscinas de caché generalmente se usan para realizar algunas tareas asincrónicas con una vida útil corta, por lo que no se usan mucho en algunos servidores de tipo de demonio orientados a la conexión.
se acabó el tiempo:
El hilo que se puede reutilizar debe ser un hilo en la piscina dentro del tiempo de espera inactivo. El tiempo de espera predeterminado es de 60 años. Si se excede la duración de este ralentí, la instancia de subproceso se terminará y se eliminará el grupo.
Finalizar:
El hilo colocado en el CachedThreadpool no tiene que preocuparse por su final. Si está inactivo después del tiempo de espera, se terminará automáticamente.
Explicación del ejemplo:
Elimine los comentarios de (2) y ejecutarlos. El resultado de la operación es el siguiente:
The first time of the first task, the third time of the third task, the third time of the second time of the second time of the second time of the second time of the second time of the second time of the second time of the second time of the second time of the second time of the second time of the second time of the third time of the third time of the second time of the second time of the second time of the third time of the second time of the second time of the second time of the second time of the second time of the second time of the second time of the second time of the second time of the second time of the second time of the second time of the second time of the second time of the second time of the second time of the second time of the second time of the second time of the second time of the second time of the second time of the second time of the second time of the second time of the second time of the second time of the second time of the second time of the second time of the second time of the second time of the second time of the second time of the second time of the second time of the second time of the second time of the second time of the second time of the second time of the second time of the second time of the second time of the second time of the second time of the second time of the second time of the second time of the second time of the second time of the second time of the second time of the second time of the second time of the second time of the second time of the fourth time of the fourth time of the fourth time of the first task, the fourth time of the fourth time of the first task, the fourth time of the fourth time of the first task, the fourth time of the fourth time of the first task, the fourth time of the fourth time of the first task, the fourth time of the fourth time of the fourth time of the first task, the fourth time of the fourth time of the fourth time of the first task, the fourth time of the fourth time of the fourth time of the first task, the fourth time of the fourth time of the fourth time of the first task, the Cuarta vez de la cuarta vez de la cuarta vez de la primera tarea, la cuarta vez de la cuarta vez de la primera tarea, la cuarta vez de la cuarta vez de la cuarta vez de la primera tarea, la cuarta vez de la cuarta vez de la cuarta vez de la primera tarea, la cuarta vez.
A partir de los resultados, se puede ver que las 4 tareas se ejecutan alternativamente.
4.2fixedThreadpool
En FixedThreadPool, hay una piscina de tamaño fijo,
Si las tareas se deben ejecutar actualmente exceden el tamaño del grupo, entonces muchas tareas salientes están en un estado de espera hasta que haya hilos gratuitos para ejecutar las tareas.
Si la tarea que actualmente debe ejecutarse es más pequeña que el tamaño del grupo, el hilo inactivo no será destruido.
Reutilizar:
FixedThreadPool es similar a Cachethreadpool, y también se puede usar si puede reutilizarse, pero no puede crear nuevos hilos en ningún momento.
Número fijo
Su singularidad es que en cualquier momento, solo puede haber un número fijo de hilos activos. En este momento, si se establece un nuevo hilo, solo se puede colocar en otra cola y esperar hasta que un hilo en el hilo actual termine y se mueva directamente fuera de la piscina.
se acabó el tiempo:
A diferencia de Cachethreadpool, FixedThreadPool no tiene un mecanismo inactivo
Use escenarios:
Por lo tanto, la mayoría de los fiestos fijos están dirigidos a algunos hilos concurrentes regulares muy estables y fijos, y se usa principalmente en servidores
Análisis del código fuente:
A juzgar por el código fuente del método, el grupo de caché y la piscina fija llaman al mismo grupo subyacente, pero los parámetros son diferentes.
El recuento de rosca de la piscina fija se fija y está inactiva de 0 segundos (sin inactivo)
El número de subprocesos de la piscina de caché es compatible
Explicación del ejemplo:
Eliminar los comentarios de (1), y el resultado de ejecución es el siguiente:
The first time of the first task, the third time of the third time of the first task, the third time of the second time of the second task, the third time of the second time of the second time of the second task, the third time of the third time of the second time of the second task, the third time of the third time of the second time of the second time of the second time of the second time of the second time of the second time of the second time of the second time of the second time of the second time of the second time of the second time of the second time of the second time of the second time of the second time of the second time of the second time of the second time of the second time of the second time of the second time of the second time of the second time of the second time of the second time of the second time of the second time of the fourth time of the fourth time of the fourth time of the fourth time of the fourth time of the fourth time of the fourth time of the fourth time of the fourth time of the fourth time of the Cuarta vez de la cuarta vez de la cuarta vez de la cuarta vez de la cuarta vez de la cuarta vez de la cuarta vez de la cuarta vez de la cuarta vez de la cuarta vez de la cuarta vez de la cuarta vez de de la cuarta vez de la cuarta vez de la cuarta vez de la cuarta vez de la cuarta vez de la cuarta vez de la cuarta vez de la cuarta vez de la cuarta vez de la cuarta vez de la cuarta vez de la cuarta vez de Cuarta vez de la cuarta vez de la cuarta vez de la cuarta vez de la cuarta vez de la cuarta vez de la cuarta vez de la cuarta vez de la cuarta vez de la cuarta vez de la cuarta vez de la cuarta vez de de la cuarta vez
Se creó un grupo de subprocesos de tamaño fijo con una capacidad de 3, y luego se ejecutaron 4 tareas en un bucle. A partir de los resultados de la salida, se puede ver que las primeras 3 tareas se ejecutaron primero, y luego los hilos inactivos realizaron la cuarta tarea.
4.3SingLethreadExecutor
Eliminar (3) comentarios. Vea el resultado de la ejecución de la siguiente manera:
The first task of the first task of the first task of the second task of the first task of the third task of the first task of the fourth task of the second task of the second task of the second task of the second task of the second task of the second task of the second task of the third task of the third task of the third task of the third task of the third task of the third task of the third task of the third task of the fourth task of the fourth task of the fourth task of the fourth task of the fourth task of the fourth task of the fourth task of the fourth task of the fourth task of the fourth task of the fourth task of the fourth task of the fourth task of the fourth task of the fourth task of the fourth task of the fourth task of the fourth task of the fourth task of the fourth task of the fourth task of the fourth task of the fourth task
Las cuatro tareas se ejecutan secuencialmente.
4.4 ProchuledThreadPool
ProchuledThreadPool es un grupo de subprocesos de tamaño fijo. Similar a FixedThreadPool, las tareas ejecutadas son tareas cronometradas.
El resultado obtenido eliminando la anotación de (4) es el mismo que el resultado obtenido por FIJETHREADPOOL. La razón principal para ProchuledThreadPool no está aquí, sino una tarea cronometrada. Vea el siguiente ejemplo:
hilo de paquete; import java.util.concurrent.executors; import java.util.concurrent.scheduledExecutorService; import java.util.concurrent.timeunit;/*** creado por Yang el 16-7-7-11. */clase pública myScheduledTask implementa runnable {private string tname; public myScheduledTask (nombre de cadena) {this.tname = name; } public void run () {System.out.println (TName+"Ejecución de retraso de tarea 2 segundos!"); } public static void main (string [] args) {ProgramedExecutorService ProchuledPool = Ejecutors.NeWSCheduledThreadPool (2); ProgramedExecutorService singschedulePool = ejecutors.newsinglethreadscheduledExecutor (); MyScheduledTask mt1 = nueva myscheduledTask ("mt1"); MyscheduledTask mt2 = new MyScheduledTask ("mt2"); // Inicie la tarea MT1 con ProchulEdThreadPool para ejecutar ProchuledPool.schedule (MT1,2, TimeUnit.Seconds); // Iniciar MT2 con SinglesCheduledThreadPool; SingschedulePool.Schedule (MT2,2000, TimeUnit.MilliseConds); ProchuledPool.shutdown (); Singschedulepool.shutdown (); }}resultado:
¡La tarea MT1 retrasa 2 segundos para ejecutar! ¡La tarea MT2 retrasa 2 segundos para ejecutar!
El resultado no se mostrará después de que el programa se ejecute durante 2 segundos, lo que indica que el hilo se ejecutó después de 2 segundos.
Gracias por leer, espero que pueda ayudarte. ¡Gracias por su apoyo para este sitio!