首页 > 技术文章 > 一种基于单例模式的任务线程池工具类

dukedu 2020-02-26 11:06 原文

 3 import java.util.concurrent.Callable;
 4 import java.util.concurrent.Executors;
 5 import java.util.concurrent.Future;
 6 import java.util.concurrent.ThreadPoolExecutor;
 7 
 8 import lombok.extern.slf4j.Slf4j;
 9 
10 /**
11  * task线程池的工具类(单例)13  *
14  * 2020年02月26日
15  * @param
16  */
17 @Slf4j
18 public class ThreadPoolManager {
19     
21     
22     private static final int THREAD_POOL_SIZE = 8;
23     
24     /**
25      * 非核心线程闲置时超时1s
26      */
27     private static final int KEEP_ALIVE = 1;
28     
29     private static ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newFixedThreadPool(THREAD_POOL_SIZE);
30     
31     private ThreadPoolManager() {
32     }
33     
34     private static class SingletonInner {
35         private static ThreadPoolManager instance = new ThreadPoolManager();
36     }
37     
38     public static ThreadPoolManager getInstance() {
39          return SingletonInner.instance;
40     }
41     
42      /**
43      * 开启一个无返回结果的线程
44      * @param r
45      */
46     public void execute(Runnable runnable) {
47         log.info("start a thread ->" + Thread.currentThread().getName());
48         // 把一个任务丢到了线程池中
49         executor.execute(runnable);
50     }
51 
52     /**
53      * 开启一个有返回结果的线程
54      * @param runnable
55      * @return
56      */
57     public <T> Future<T> submit(Callable<T> runnable) {
58         // 把一个任务丢到了线程池中
59         return executor.submit(runnable);
60     }
61  
62     /**
63      * 把任务移除等待队列
64      * @param runnable
65      */
66     public void cancel(Runnable runnable) {
67         if (runnable != null) {
68             executor.getQueue().remove(runnable);
69         }
70     }
71     
72     /**
73      * 获取空闲线程数
74      * @return
75      */
76     public static int getFreeThreadNum() {
77         int freeNum = executor.getCorePoolSize() -executor.getActiveCount();
78         return freeNum;
79     }
80     
81 }

 

推荐阅读