Java Thread Pool ExecutorService
1. Piscine de filetage
1.1 Dans quelles circonstances utilisez-vous le pool de threads?
1.2 Avantages de l'utilisation de pools de threads
2.Exécuteur-service et exécuteur
2.1 Introduction
ExecutorService est une interface qui hérite de l'exécuteur
Interface publique ExecutorService étendez l'exécuteur exécuteur {}L'exécuteur est également une interface, qui ne contient qu'une seule méthode:
Exécuteur de l'interface publique {void execute (Commande Runnable);} L'interface de niveau supérieur du pool de threads en Java est excutor, mais à proprement parler >> L'expecteur n'est pas un pool de threads, mais juste un outil pour exécuter des threads. L'interface réelle du thread> Pool est ExecutorService.
3.EXECURS
Il s'agit d'une classe d'usine statique, qui peut produire différents types de pools de fil, et certains des codes source sont les suivants:
Exécuteurs de classe publique {// newFixedThreadPoolPublic Static ExecutorService newFixEdThreadpool (int nthreads) {return new ThreadPoolExecutor (nthreads, nthreads, 0l newCachedThreadPool () {return new ThreadPoolExecutor (0, Integer.max_value, 60L, timeunit.seconds, new synchronouseue <runnable> ()); } // newscheduledThreadpool public static scheduledexEcutService newscheduledThreadpool (int corepoolSize) {return new scheduledThreadPoolExecutor (corePoolSize); } // Newstringooo}Examinons d'abord un exemple spécifique et utilisons des exemples pour illustrer les similitudes et les différences entre elles.
Thread de package; import java.util.concurrent.executorService; import java.util.concurrent.executors; import java.util.concurrent.scheduledexecutorService; / ** * créé par Yang le 16-7-11. * / public class ch09_executor {private static void run (exécutor-service threadpool) {for (int i = 1; i <5; i ++) {final int tasid = i; threadpool.execute (new runnable () {@Override public void run () {for (int i = 1; i <5; i ++) {try {thread.sleep (20);} catch (interruptedException e) {e.printstackTrace ();} System.out.println ("+ taskid +" exécution "de la tâche); ThreadPool.shutdown (); Pool de fil d'un seul thread. Run (FixedThreadPool); // (2) // run (singleThreadpool); // (3) // Run (ScheduledThreadPool); // (4)}}4. 4 Pools de fil couramment utilisés
4.1 CachedThreadpool
CacheThreadpool créera une zone de cache qui met en cache le fil initialisé, termine et supprime les fils qui n'ont pas été utilisés pendant 6 secondes du cache.
Si le fil est disponible, utilisez le fil qui a été créé auparavant. Si le fil n'est pas disponible, créez un nouveau fil.
.Reuse:
Pool de type cache, vérifiez d'abord s'il y a des threads qui ont été créés dans la piscine. S'il y en a un, réutilisez. S'il n'y a personne, créez un nouveau fil et ajoutez-le à la piscine.
Utilisez des scénarios:
Les pools de cache sont généralement utilisés pour effectuer certaines tâches asynchrones avec des durées de vie courtes, ils ne sont donc pas beaucoup utilisés dans certains serveurs de type démon axé sur la connexion.
temps mort:
Le fil qui peut être réutilisé doit être un fil dans la piscine dans le délai d'attente. Le délai d'expiration par défaut est de 60s. Si la durée de ce ralenti est dépassée, l'instance de thread sera terminée et le pool sera supprimé.
Finition:
Le fil mis dans le CachedThereadpool n'a pas à s'inquiéter de sa fin. S'il est inactif après le temps mort, il sera automatiquement terminé.
Exemple d'explication:
Supprimez les commentaires de (2) et exécutez-les. Le résultat de l'opération est le suivant:
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 Quatrième fois de la quatrième fois de la quatrième fois de la première tâche, la quatrième fois de la quatrième fois de la première tâche, la quatrième fois de la quatrième fois de la quatrième fois de la première tâche, la quatrième fois de la quatrième fois de la quatrième fois de la première tâche, la quatrième fois
D'après les résultats, on peut voir que les 4 tâches sont exécutées alternativement.
4.2FixEdThreadpool
Dans FixedThreadpool, il y a une piscine de taille fixe,
Si les tâches doivent actuellement être exécutées dépassent la taille du pool, de nombreuses tâches sortantes sont dans un état d'attente jusqu'à ce qu'il y ait des threads libres pour exécuter les tâches.
Si la tâche qui doit être exécutée actuellement est plus petite que la taille du pool, le fil inactif ne sera pas détruit.
Réutilisation:
FIXTTHERRENDPOOL est similaire à Cachethreadpool, et il peut également être utilisé s'il peut être réutilisé, mais vous ne pouvez pas créer de nouveaux fils à tout moment.
Nombre fixe
Son caractère unique est qu'à tout moment, il ne peut y avoir qu'un nombre fixe de threads actifs. Pour le moment, s'il y a un nouveau fil à établir, il ne peut être placé que dans une autre file d'attente et attendre qu'un fil dans le fil actuel se termine et est déplacé directement de la piscine.
temps mort:
Contrairement à Cachethreadpool, FixedTheredpool n'a pas de mécanisme inactif
Utilisez des scénarios:
Par conséquent, la plupart des threads FixedTheredpool s'adressent à des fils simultanés réguliers très stables et fixe, et est principalement utilisé dans les serveurs
Analyse du code source:
À en juger par le code source de la méthode, le pool de cache et le pool fixe appellent le même pool sous-jacent, mais les paramètres sont différents.
Le nombre de filetages de piscine fixe est fixe et est de 0 seconde inactif (pas de ralenti)
Le nombre de threads de pool de cache prend en charge 0-iteger.max_value (évidemment, la tolérance aux ressources de l'hôte n'est pas du tout considérée), 60 secondes inactives
Exemple d'explication:
Supprimer les commentaires de (1), et le résultat en cours d'exécution est le suivant:
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 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 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 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 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 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 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 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 fourth time de la quatrième fois
Un pool de threads de taille fixe a été créé avec une capacité de 3, puis 4 tâches ont été exécutées en boucle. À partir des résultats de sortie, on peut voir que les 3 premières tâches ont été exécutées en premier, puis les threads inactifs ont effectué la quatrième tâche.
4.3SingthereadExEcutor
Supprimer (3) commentaires. Voir le résultat d'exécution comme suit:
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 La quatrième tâche de la quatrième tâche de la quatrième tâche de la quatrième tâche de la quatrième tâche de la quatrième tâche de la quatrième tâche de la quatrième tâche de la quatrième tâche de la quatrième tâche de la quatrième tâche de la quatrième tâche de la quatrième tâche de la quatrième tâche de la quatrième tâche de la quatrième tâche de la quatrième tâche de la quatrième tâche de la quatrième tâche de la quatrième tâche de la quatrième tâche de la quatrième tâche de la quatrième tâche
Les quatre tâches sont exécutées séquentiellement.
4.4 ScheduledThreadpool
ScheduledThreadPool est un pool de threads de taille fixe. Semblable à FixedThreadpool, les tâches exécutées sont des tâches chronométrées.
Le résultat obtenu en supprimant l'annotation de (4) est le même que le résultat obtenu par FIXETHERRENDPOOL. La raison principale de ScheduledThreadpool n'est pas là, mais une tâche chronométrée. Voir l'exemple suivant:
Thread de package; Importer java.util.concurrent.executors; import java.util.concurrent.scheduleExEcutorService; import java.util.concurrent.timeunit; / ** * créé par Yang le 16-7-11. * / public class MyScheduledTask implémente Runnable {private String tname; public myScheduledTask (String name) {this.tname = name; } public void run () {System.out.println (tname + "Tâche Retard Exécution 2 secondes!"); } public static void main (String [] args) {ScheduleDexeCutOrService scheduledPool = exécutors.newScheduledThreadPool (2); ScheduleDExECUTORService SingschedulePool = exécuteurs.NewSingLetHreadScheDuleDeDExECUTOR (); MyScheduledTask mt1 = new myScheduledTask ("MT1"); MyScheduledTask mt2 = new myScheduledTask ("mt2"); // Démarrez la tâche MT1 avec ScheduledThreadPool pour exécuter ScheduledPool.Schedule (MT1,2, TimeUnit.seconds); // Démarrer MT2 avec SinglescheduledThreadpool; Singschedulepool.schedule (MT2,2000, timeUnit.Millisecondes); ScheduledPool.shutdown (); Singschedulepool.shutdown (); }}résultat:
Tâche MT1 retarde 2 secondes à exécuter! MT2 Tâche retarde 2 secondes à exécuter!
Le résultat ne sera pas affiché après l'exécution du programme pendant 2 secondes, indiquant que le thread a été exécuté après 2 secondes.
Merci d'avoir lu, j'espère que cela peut vous aider. Merci pour votre soutien à ce site!