通用线程池1
1 public class CommonThreadPool { 2 private static final CommonThreadPool pool = new CommonThreadPool(); 3 private ThreadPoolExecutor executor; 4 private CommonThreadPool() { 5 int corePoolSize = 4; 6 int maximumPoolSize = 4; 7 int workQueue = 500; 8 executor = new ThreadPoolExecutor(corePoolSize, maximumPoolSize, 30000L, TimeUnit.MILLISECONDS, 9 new LinkedBlockingQueue<>(workQueue), 10 new ThreadPoolExecutor.DiscardPolicy()); 11 executor.allowCoreThreadTimeOut(true); 12 } 13 14 public static CommonThreadPool getInstance() { 15 return pool; 16 } 17 18 /** 19 * 添加带返回结果的任务(具体的线程任务需实现Callable接口) 20 */ 21 public <M> Future <M> add(Callable<M> task) { 22 return executor.submit(task); 23 } 24 25 /** 26 * 添加无返回结果的任务(具体的线程任务需实现Runnable接口) 27 */ 28 public void add(Runnable task) { 29 executor.execute(task); 30 } 31 }
- 该线程池使用到了单例模式(饿汉模式)
- 线程池自定义了最大线程数、核心线程数、线程排队数,以及当线程排队超过限制时对超出部分线程的处理策略(这里是直接丢弃)
- 使用该线程池时,根据具体任务的类型,选择带返回结果或不带返回结果的方法