1. 创建线程池的类,封装一个线程池对象
public class MyThreadPool { private ThreadPoolExecutor mExecutor; private int mCorePoolSize; private int mMaximumPoolSize; private long mKeepAliveTime; // constructor method public MyThreadPool(int corePoolSize, int maximumPoolSize, long keepAliveTime) { mCorePoolSize = corePoolSize; mMaximumPoolSize = maximumPoolSize; mKeepAliveTime = keepAliveTime; initThreadPoolExecutor(); // 初始化线程池对象 } // 提交线程,提交的方法会返回一个furture对象,通过这个对象能够判断线程运行的状态,而execute方法没有返回值,直接执行 public Future<?> submit(Runnable task) { return mExecutor.submit(task); } // create a new executor while mexecutor is null, shutdowned, terminated private void initThreadPoolExecutor() { if (mExecutor == null || mExecutor.isShutdown() || mExecutor.isTerminated()) { synchronized (MyThreadPool.class) { int corePoolSize = mCorePoolSize; // 核心线程数 int maximumPoolSize = mMaximumPoolSize; // 最大线程数 long keepAliveTime = mKeepAliveTime; // 线程在运行完了之后不会被销毁的时间 TimeUnit unit = TimeUnit.MILLISECONDS; // 时间单元,上面那个保持活动的时间的单位 // 下面三个是不常改动的,所以保持不变就行,具体需求再查文档 BlockingQueue<Runnable> workQueue = new LinkedBlockingQueue<>(); ThreadFactory factory = Executors.defaultThreadFactory(); RejectedExecutionHandler handler = new ThreadPoolExecutor.DiscardPolicy(); // 初始化线程池对象 mExecutor = new ThreadPoolExecutor( corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, factory, handler ); } } } public void remove(Runnable task) { mExecutor.remove(task); } public void execute(Runnable command) { mExecutor.execute(command); } }
2. 通过一个工厂类来维护实际使用的线程池,使用的时候直接工厂类调用静态方法就行
public class MyThreadPoolFactory { private static MyThreadPool mNormalThreadPool; private static MyThreadPool mDownloadThreadPool; // ui thread pool public static MyThreadPool createNormalThreadPool() { if (mNormalThreadPool == null) { synchronized (MyThreadPoolFactory.class) { if (mNormalThreadPool == null) { // 5个核心线程,最大五个线程,线程keepalive的时间是3秒 mNormalThreadPool = new MyThreadPool(5, 5, 3000); } } } return mNormalThreadPool; } // download thread pool public static MyThreadPool createDownloadThreadPool() { if (mDownloadThreadPool == null) { synchronized (MyThreadPoolFactory.class) { if (mDownloadThreadPool == null) { mDownloadThreadPool = new MyThreadPool(5, 5, 3000); } } } return mDownloadThreadPool; } }