封装了各种类型的线程池,方便直接使用
看下有哪些类型:
默认线程池,搜索模块专用线程池,网络请求专用线程池,U盘更新,同步SDK读写操作线程池,日志打印使用线程池
DEFALUT,SEARCH,NET_WORK,UDISK_DOWNLOAD,SDK_IO,LOG_PRINT
看下有哪些优先级级别
UI_TOP, UI_NORMAL, UI_LOW, DEFAULT, BG_TOP, BG_NORMAL, BG_LOW;
一:实现默认线程池
接下来先实现一个 默认实现 等待队列, 优先级比较,核心线程数等的线程池
开放 核心线程数,线程创建的工厂类(可以定制线程的优先级)供 外部定制(你也可以开放更多的参数)
public class TaskPriorityExecutor implements Executor { private static final int CORE_POOL_SIZE = 3; private static final int CPU_COUNT = Runtime.getRuntime().availableProcessors(); private static final int MAXIMUM_POOL_SIZE = CPU_COUNT * 2 + 1; private static final int KEEP_ALIVE = 30; private static final Comparator<Runnable> RUNNABLE_COMPARATOR = new Comparator<Runnable>() { @Override public int compare(Runnable lhs, Runnable rhs) { if (lhs instanceof TaskPriorityRunnable && rhs instanceof TaskPriorityRunnable) { return ((TaskPriorityRunnable) lhs).priority.ordinal() - ((TaskPriorityRunnable) rhs).priority.ordinal(); } else { return 0; } } }; private final BlockingQueue<Runnable> mPoolWorkQueue = new PriorityBlockingQueue<Runnable>(MAXIMUM_POOL_SIZE, RUNNABLE_COMPARATOR); private final ThreadPoolExecutor mThreadPoolExecutor; public TaskPriorityExecutor() { this(CORE_POOL_SIZE, new TaskThreadFactory("Defalut")); } public TaskPriorityExecutor(int poolSize, ThreadFactory threadFactory) { mThreadPoolExecutor = new ThreadPoolExecutor( poolSize, MAXIMUM_POOL_SIZE, KEEP_ALIVE, TimeUnit.SECONDS, mPoolWorkQueue, threadFactory); } /** * 该构造器会创建单线程池执行任务 */ public TaskPriorityExecutor(ThreadFactory threadFactory) { mThreadPoolExecutor = new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>(), threadFactory); } public int getPoolSize() { return mThreadPoolExecutor.getCorePoolSize(); } public void setPoolSize(int poolSize) { if (poolSize > 0) { mThreadPoolExecutor.setCorePoolSize(poolSize); } // Executors.newCachedThreadPool() // Executors.newFixedThreadPool() // Executors.newScheduledThreadPool() // Executors.newSingleThreadExecutor() // Executors.newSingleThreadScheduledExecutor() } public ThreadPoolExecutor getThreadPoolExecutor() { return mThreadPoolExecutor; } /** * 线程池忙 */ public boolean isBusy() { return mThreadPoolExecutor.getActiveCount() >= mThreadPoolExecutor.getCorePoolSize(); } /** * 线程池超载 */ public boolean isFull() { return mThreadPoolExecutor.getActiveCount() >= mThreadPoolExecutor.getCorePoolSize() * 2; } public boolean isShutdown(){ return mThreadPoolExecutor.isShutdown(); } @Override public void execute(final Runnable r) { mThreadPoolExecutor.execute(r); }
二 根据接口定制业务场景的线程池接口
接下来我们就开始根据开放的接口来根据不同的业务需要来配置自己的线程池
final class TaskProxy< extends Task<ResultType> { private final Task<ResultType> task; private Executor executor; /*package*/ static final InternalHandler INTERNAL_HANDLER = new InternalHandler(); static TaskPriorityExecutor sDefaultExecutor = new TaskPriorityExecutor(); static TaskPriorityExecutor sSearchExecutor = null; sta