ThreadPoolExecutor thread execution service for Java concurrency and java multi-thread concurrent execution
1 package com. thread. test. thread; 2 3 import java. util. concurrent. executorService; 4 import java. util. concurrent. define blockingqueue; 5 import java. util. concurrent. rejectedExecutionHandler; 6 import java. util. concurrent. threadLocalRandom; 7 import java. util. concurrent. threadPoolExecutor; 8 import java. util. concurrent. timeUnit; 9 10/** 11 * ThreadPoolExecutor12 * ExecutorService of the submitted task through the thread pool, usually by the Exe Cutors generates 13 * High-concurrency tasks, which are efficient because it reduces the waiting time for tasks and well manages the resources required for execution, including threads, some basic task execution data of the maintainer. For example, the number of completed tasks is 15*16 * ThreadPoolExecutor. There are many tunable parameters that can be used for different purposes, however, we usually use 17 * Executors # newCachedThreadPool without capacity restrictions, automatic Thread recovery 18 * Executors # newFixedThreadPool fixed capacity Thread Pool 19 * Executors # newSingleThreadExecutor single thread 20 * many parameters are preset for many common scenarios, 21*22 * Hello world! 23*24 */25 public class ThreadPoolFactoryTest26 {27 public static void main (String [] args) 28 {29/** 30 * @ int corePoolSize: Number of threads maintained in the thread pool, the life cycle is the same as that of the thread pool, unless allowCoreThreadTimeOut31 * @ int maximumPoolSize is set: the maximum number of allowed 32 * @ long keepAliveTime: Maximum allowed survival time 33 * @ TimeUnit unit: unit 34 * @ BlockingQueue <Runnable> workQueue: stores the tasks awaiting execution. The Runnable type tasks submitted by execute are 35 * @ RejectedExecutionHandler: thread blocking, the operation 36 */37 ExecutorService enew = new ThreadPoolExecutor (5, 20, 0L, 38 TimeUnit. SECONDS, 39 new LinkedBlockingQueue <Runnable> (), 40 new RejectedExecutionHandler () {41 public void rejectedExecution (Runnable r, ThreadPoolExecutor executor) {42 System. out. println ("this is the exception execution begin"); 43 executor.exe cute (r); 44 System. out. println ("this is the exception execution end"); 45} 46}); 47 48 for (int I = 0; I <100; I ++) {49 enew.exe cute (new Runnable () {50 public void run () {51 int l = ThreadLocalRandom. current (). nextInt (); 52 System. out. println ("task... "+ l +" begin "); 53 try {54 Thread. sleep (2000); 55 System. out. println ("task... "+ l +" end "); 56} catch (InterruptedException e) {57 e. printStackTrace (); 58} 59} 60}); 61} 62 System. out. println ("add end... "); 63} 64}
Project address: https://github.com/windwant/threadtest