Introdução a vários métodos de implementação e diferenças do pool de threads java
importar java.Text.DateFormat; importar java.text.simpledEformat; importar java.util.arraylist; importar java.util.date; importar java.util.list; importação java.util.list; import java.util.Concurrent.calable; importação; java.util.concurrent.Executors;import java.util.concurrent.Future;public class TestThreadPool { // -newFixedThreadPool is similar to cacheThreadPool, and can also be used if it is reuse, but it cannot create new threads at any time // - Its uniqueness: at any point in time, at most, there can be a fixed number of active threads. At this time, if there is a new thread to be established, it can only be placed in another queue and wait until a thread in the current thread terminates and is moved out of the pool directly // - Unlike cacheThreadPool, FixedThreadPool does not have an IDLE mechanism (it may also be there, but since the document does not mention it, it must be very long, similar to TCP or UDP // IDLE mechanism that depends on the upper layer), so O FIXTHREADPOOL é destinado principalmente a alguns fios simultâneos regulares muito estáveis e fixos, usados principalmente em servidores // - a partir do código -fonte do método, o pool de cache e corrigido o pool chama o mesmo pool subjacente, mas os parâmetros são diferentes: // a contagem de rosca fixa é fixa e é 0 segundos (não) // o cache (/ a contagem de roscas de cache é fixo e a contagem de roscas é fixa e a contagem de threads de cache. considerado de maneira alguma), 60 Second Idle Private Static ExecorsService fIllService = executores.NewfixedThreadpool (6); // -cache pool, primeiro verifique se existem threads estabelecidos anteriormente no pool, se houver, reutilize. Caso contrário, crie um novo thread e adicione-o ao pool // -cache pool é geralmente usado para executar algumas tarefas assíncronas com vida útil muito curta // Portanto, ele não é usado em alguns servidores do tipo Daemon Orientado a conexão. // - o thread que pode reutilizar deve ser um thread no pool dentro do tempo limite ocioso. O tempo limite padrão é dos anos 60. Se o tempo ocioso exceder a duração, a instância do thread será encerrada e movida para fora da piscina. // Observe que o fio colocado no cachedThreadpool não precisa se preocupar com o fim. Se estiver inativo após o tempo limite, será encerrado automaticamente. Executores estáticos privados CacheService = executores.newcachedthreadpool (); // -Singleton Thread, pode haver apenas um thread a qualquer momento do pool // -o pool subjacente é o mesmo que o pool de cache e o pool fixo, mas o número de threads é de 1-1,0 segundos de marcha lenta (sem ociosidade) de executores estática privada singleService = executores.NewsingLethreadExExExEstor (); // -Scheduled Thread Pool // -Os threads neste pool podem ser atrasados na sequência de acordo com o cronograma, ou o STATIC STATIC STATION SGONDULEDSERVICE = executores.newscheduledthreadpool (10); public static void main (string [] args) {dateFormat format = new SimpleDateFormat ("yyyy-mm-dd hh: mm: ss"); List <Teger> CustomerList = new ArrayList <Teger> (); System.out.println (format.format (new Date ())); testFixedThreadpool (FILLSERVICE, CLIENTELIST); System.out.println ("------------------------"); testFixedThreadpool (FILLSERVICE, CLIENTELIST); fIllService.shutdown (); System.out.println (fixaService.ISSHUTDOWN ()); System.out.println ("--------------------------------------------------"); testCachethreadpool (CacheService, Customerlist); System.out.println ("--------------------------------------------------"); testCachethreadpool (CacheService, Customerlist); CacheService.shutdownNow (); System.out.println ("--------------------------------------------------"); testsingleServicethreadpool (SinglesService, CustomerList); testsingleServicethreadpool (SinglesService, CustomerList); SingleService.shutdown (); System.out.println ("--------------------------------------------------"); testscheduledServicethreadpool (ScheduledService, CustomerList); testscheduledServicethreadpool (ScheduledService, CustomerList); ScheduledService.shutdown (); } public static void testScheduledServicethReadpool (Serviço de ExecutorService, List <Integer> CustomerList) {List <Plinable <Teger>> listCallable = new ArrayList <Callable <Teger>> (); para (int i = 0; i <10; i ++) {Callable <Teger> callable = new Callable <Teger> () {@Override public Integer Call () lança exceção {retorna new Random (). NextInt (10); }}; listCallable.add (chamável); } tente {list <future <Teger>> listfuture = service.invoKeall (listCallable); para (futuro <Integer> futuro: listfuture) {integer id = futuro.get (); clientelist.add (id); }} catch (Exceção e) {e.printStackTrace (); } System.out.println (CustomerList.toString ()); } public static void testsingleServicethReadpool (ExecutorService Service, List <Teger> CustomerList) {List <Callable <List <Teger>>> listCallable = new ArrayList <Callable <List <Teger>>> (); para (int i = 0; i <10; i ++) {Callable <List <Teger>>> Callable = new Callable <List <Teger>> () {@Override public List <Teger> Call () lança exceção {List <Teger> List = getList (new Random (). NextInt (10)); boolean isStop = false; while (list.size ()> 0 &&! isStop) {System.out.println (thread.currentThread (). getId () + " - sono: 1000"); isStop = true; } Lista de retorno; }}; listCallable.add (chamável); } tente {list <futuro <list <Teger>>> listfuture = service.inVokeall (listCallable); para (Future <List <Integer>> futuro: listfuture) {list <Teger> list = FUTURO.GET (); CustomerList.addall (lista); }} catch (Exceção e) {e.printStackTrace (); } System.out.println (CustomerList.toString ()); } public static void testCachethReadpool (ExecutorService Service, List <Teger> CustomerList) {List <Callable <List <Teger>>> listCallable = new ArrayList <Callable <List <Teger>> (); para (int i = 0; i <10; i ++) {Callable <List <Teger>> Callable = new Callable <List <Teger>> () {@Override public List <Teger> Call () lança exceção {List <Teger> List = getList (new Random (). NextInt (10)); boolean isStop = false; while (list.size ()> 0 &&! isStop) {System.out.println (thread.currentThread (). getId () + " - sono: 1000"); isStop = true; } Lista de retorno; }}; listCallable.add (chamável); } tente {list <futuro <list <Teger>>> listfuture = service.inVokeall (listCallable); para (Future <List <Integer>> futuro: listfuture) {list <Teger> list = FUTURO.GET (); CustomerList.addall (lista); }} catch (Exceção e) {e.printStackTrace (); } System.out.println (CustomerList.toString ()); } public static void testFixedThreadpool (ExecutorService Service, List <Teger> CustomerList) {list <Callable <List <Teger>>> listCallable = new ArrayList <Callable <List <Teger>>> (); para (int i = 0; i <10; i ++) {Callable <List <Teger>> Callable = new Callable <List <Teger>> () {@Override public List <Teger> Call () lança exceção {List <Teger> List = getList (new Random (). NextInt (10)); boolean isStop = false; while (list.size ()> 0 &&! isStop) {System.out.println (thread.currentThread (). getId () + " - sono: 1000"); isStop = true; } Lista de retorno; }}; listCallable.add (chamável); } tente {list <futuro <list <Teger>>> listfuture = service.inVokeall (listCallable); para (Future <List <Integer>> futuro: listfuture) {list <Teger> list = FUTURO.GET (); CustomerList.addall (lista); }} catch (Exceção e) {e.printStackTrace (); } System.out.println (CustomerList.toString ()); } Lista estática pública <Integer> getList (int x) {list <Teger> list = new ArrayList <Teger> (); list.add (x); list.add (x * x); lista de retorno; }}Uso: LinkedBlockingQueue para implementar a explicação do pool de threads
/Por exemplo: CorePoolSize = 3, MaximumPoolSize = 6, LinkedBlockingQueue (10) // RejejeexecutionHandHandler O método de processamento padrão é: ThreadPoolExecutor.abortpolicy // threadpoolExecutor executService = new threadPoolitor (CorePoolSize, MaximumpoolSize, 1LlOlLl, 1lLl, 1LlOlLl, LinkedBlockingQueue <unnable> (10)); // 1. Se o thread em execução no pool de threads (ou seja, chamando executorService.execute) não atingir o LinkedBlockQueue.init (10), o número de threads atualmente executados é: CorePoolSize (3) // 2. Se o número de threads excedeu o LinkedBlockEue.init (10) e excedido> = init (10)+CorePoolSize (3) e for menor que o init (10)+MaximumPoolSize. O número de threads iniciados atualmente é: (threads atuais (10)) // 3. Se o número de threads chamado exceder o init (10)+MaximumPoolSize, isso for tratado de acordo com as regras do rejeição de rejeição.
Sobre: Explicação de várias implementações padrão do rejejeTexecutionHandler
// O padrão é usado: Threadpoolexecutor.abortpolicy. O manipulador é rejeitado e lançará um tempo de execução rejeitEdExecutionException. RejeitEdExecutionHandler Policy = new ThreadPoolExecutor.abortpolicy (); //// em threadpoolExecutor.callerRunspolicy, o thread se chama de execução que executa a tarefa. Essa estratégia fornece um mecanismo de controle de feedback simples que pode retardar o envio de novas tarefas. // Policy = new ThreadPoolexecutor.CallERRUNSPOLICY (); //// em threadpoolexecutor.discardpolicy, tarefas que não podem ser executadas serão excluídas. // Policy = new Threadpoolexecutor.discardpolicy (); //// em threadpoolexecutor.discardoldestpolicy, se o executor não tiver sido fechado, a tarefa à frente da fila de trabalho será excluída e a execução do programa será retirada (repetir esse processo se falhar novamente). // Policy = new Threadpoolexecutor.discardoldestpolicy ();
A introdução acima aos métodos de implementação e diferenças do pool de threads Java é todo o conteúdo que compartilhei com você. Espero que você possa lhe dar uma referência e espero que você possa apoiar mais o wulin.com.