Java Thread Pool ExecorsService
1. Pool de threads
1.1 Em que circunstâncias você usa o pool de threads?
1.2 Benefícios do uso de pools de threads
2.ExecutorService e executores
2.1 Introdução
ExecutorService é uma interface que herda o executor,
Public Interface ExecorService Extend Executor {}Executor também é uma interface, que contém apenas um método:
Executor de interface pública {void Execute (comando runnable);} A interface de nível superior do pool de threads em Java é o exclusivo, mas estritamente falando >> Exector não é um pool de threads, mas apenas uma ferramenta para executar threads. A interface do thread> do thread> é o ExecorService.
3.Exutores
É uma classe de fábrica estática, que pode produzir diferentes tipos de pools de threads, e alguns dos códigos de origem são os seguintes:
Classe public Executores {// newFixedThreadPoolpublic estático ExecutSerService newFixedThreadpool (int nthreads) {Return New ThreadPoolExecutor (NTHRADs, NTHREADS, 0L, ExclemAnit.MillisEconds, New LinkDBlockingQueue <unnable> ()); newcachedThreadpool () {return new ThreadPoolExecutor (0, Integer.max_value, 60L, timeUnit.Seconds, novo síncronoSqueue <uncrnable> ()); } // NewsCheduledThreadpool estático de estática agendada dentexecutorService NewsChedulEdThreadpool (int CorePoolSize) {return new ScheduledThreadPoolExecutor (CorePoolSize); } // newstringooo}Vamos primeiro olhar para um exemplo específico e usar exemplos para ilustrar as semelhanças e diferenças entre eles.
Pacote Thread; importar java.util.concurrent.executorService; importar java.util.concurrent.executores; importar java.util.concurrent.scheduledExecutorService;/*** Criado por Yang em 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);} catch (interruptException e) {e.printStacktrace ();} system.out.println ("+TaskId+" extrace "; ThreadPool.shutdown (); Pool de um único thread. executar (fixaThreadpool); // (2) // Run (SingleThreadpool); // (3) // Run (ScheduledThreadpool); // (4)}}4. 4 Pools de threads comumente usados
4.1 CachedThreadpool
O CachedThreadpool criará uma área de cache que armazena em armazenamento o encadeamento inicializado, termina e remove threads que não foram usados por 6 segundos do cache.
Se o thread estiver disponível, use o thread que foi criado antes. Se o thread não estiver disponível, crie um novo thread.
.Reuse:
Pool do tipo cache, primeiro verifique se há threads que foram criados no pool. Se houver um, reutilize. Se não houver ninguém, crie um novo thread e adicione -o ao pool.
Use cenários:
Os pools de cache geralmente são usados para executar algumas tarefas assíncronas com vida útil curta, para que não sejam usadas muito em alguns servidores do tipo Daemon orientados para a conexão.
tempo esgotado:
O thread que pode ser reutilizado deve ser um thread no pool dentro do tempo limite ocioso. O tempo limite padrão é dos anos 60. Se a duração dessa marcha lenta for excedida, a instância do encadeamento será encerrada e o pool será removido.
Terminar:
O fio colocado no CachedThreadpool não precisa se preocupar com o fim. Se estiver inativo após o tempo limite, será encerrado automaticamente.
Exemplo de explicação:
Remova os comentários de (2) e execute -os. O resultado da operação é o seguinte:
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 Quarta vez da quarta vez da quarta vez da primeira tarefa, a quarta vez da quarta vez da primeira tarefa, a quarta vez da quarta vez da quarta vez da primeira tarefa, a quarta vez da quarta vez da quarta vez da primeira tarefa, a quarta vez
A partir dos resultados, pode -se observar que as 4 tarefas são executadas alternadamente.
4.2FIXEDTHREADPOOL
No FILLTHREADPOOL, há um pool de tamanho fixo,
Se as tarefas atualmente precisarem ser executadas, exceder o tamanho do pool, muitas tarefas de saída estarão em um estado de espera até que haja threads gratuitos para executar as tarefas.
Se a tarefa atualmente necessária para ser executada for menor que o tamanho da piscina, o encadeamento ocioso não será destruído.
Reutilizar:
O FILLTHREADPOOL é semelhante ao Cachethreadpool e também pode ser usado se puder ser reutilizado, mas você não pode criar novos threads a qualquer momento.
Número fixo
Sua singularidade é que, em qualquer momento, só pode haver um número fixo de encadeamentos ativos. No momento, se houver um novo thread a ser estabelecido, ele só poderá ser colocado em outra fila e aguarde até que um thread no thread atual termine e seja movido para fora diretamente da piscina.
tempo esgotado:
Ao contrário de Cachethreadpool, o FILLTHREADPOOL não possui um mecanismo ocioso
Use cenários:
Portanto, a maioria das vezes fixo é direcionada a alguns threads simultâneos regulares muito estáveis e fixos e é usada principalmente em servidores
Análise de código -fonte:
A julgar pelo código -fonte do método, o pool de cache e o pool fixo chamam o mesmo pool subjacente, mas os parâmetros são diferentes.
A contagem de roscas fixa da piscina é fixa e está em 0 segundos de marcha lenta (sem marcha lenta)
O número de threads de cache do pool suporta 0-integer.max_value (obviamente, a tolerância de recursos do host não é considerada), 60 segundos ociosos
Exemplo de explicação:
Remova os comentários de (1), e o resultado em execução é o seguinte:
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 da quarta vez
Um pool de threads de tamanho fixo foi criado com uma capacidade de 3 e, em seguida, 4 tarefas foram executadas em um loop. A partir dos resultados da saída, pode -se observar que as três primeiras tarefas foram executadas primeiro e, em seguida, os threads ociosos executaram a quarta tarefa.
4.3SingleThreadExecutor
Remova (3) comentários. Veja o resultado da execução da seguinte forma:
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 A quarta tarefa da quarta tarefa da quarta tarefa da quarta tarefa da quarta tarefa da quarta tarefa da quarta tarefa da quarta tarefa da quarta tarefa da quarta tarefa da quarta tarefa da quarta tarefa da quarta tarefa da quarta tarefa da quarta tarefa da quarta tarefa da quarta tarefa da quarta tarefa da quarta tarefa da quarta tarefa da quarta tarefa da quarta tarefa da quarta tarefa da quarta tarefa da quarta tarefa da quarta tarefa da quarta tarefa do quarto dia
As quatro tarefas são executadas sequencialmente.
4.4 ScheduledThreadpool
ScheduledThreadpool é um pool de threads de tamanho fixo. Semelhante ao FILLTHREADPOOL, as tarefas executadas são tarefas cronometradas.
O resultado obtido removendo a anotação de (4) é o mesmo que o resultado obtido pelo FILLTHREADPOOL. O principal motivo do ScheduledThreadpool não está aqui, mas uma tarefa cronometrada. Veja o seguinte exemplo:
Thread Package; importar java.util.concurrent.executores; importar java.util.concurrent.scheduledExecutorService; importar java.util.concurrent.timeunit;/*** Criado por Yang em 16-7-11. */classe pública myScheduledTask implementa Runnable {private string tname; public myScheduledTask (nome da string) {this.tname = name; } public void run () {System.out.println (TNAME+"Execução de atraso da tarefa 2 segundos!"); } public static void main (string [] args) {scheduledExecutorService scheduledpool = executores.newscheduledThreadpool (2); ScheduledExecutorService SingschedulePool = executores.NewsingleThreadScheduleDexecutor (); MyScheduledTask mt1 = new MyScheduledTask ("mt1"); MyScheduledTask mt2 = new MyScheduledTask ("mt2"); // Inicie a tarefa MT1 com o ScheduledThreadpool para executar o ScheduledPool.schedule (mt1,2, timeUnit.SECONDS); // Inicie o mt2 com singlescheduledthreadpool; singschedulepool.schedule (mt2,2000, timeUnit.millisEconds); scheduledpool.shutdown (); singschedulepool.shutdown (); }}resultado:
MT1 Tarefa atrasa 2 segundos para executar! MT2 Tarefa atrasa 2 segundos para executar!
O resultado não será exibido após a execução do programa por 2 segundos, indicando que o thread foi executado após 2 segundos.
Obrigado pela leitura, espero que isso possa ajudá -lo. Obrigado pelo seu apoio a este site!