定义一个新的 ThreadPool

ThreadPool 是一个 ExecutorService,它使用可能的几个池化线程之一执行每个提交的任务,通常使用 Executors 工厂方法配置。

以下是将新 ThreadPool 初始化为在你的应用中使用的单例的基本代码:

public final class ThreadPool {

    private static final String TAG = "ThreadPool";
    private static final int CORE_POOL_SIZE = 4;
    private static final int MAX_POOL_SIZE = 8;
    private static final int KEEP_ALIVE_TIME = 10; // 10 seconds
    private final Executor mExecutor;

    private static ThreadPool sThreadPoolInstance;

    private ThreadPool() {
        mExecutor = new ThreadPoolExecutor(
            CORE_POOL_SIZE, MAX_POOL_SIZE, KEEP_ALIVE_TIME,
            TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>());
    }

    public void execute(Runnable runnable) {
        mExecutor.execute(runnable);
    }

    public synchronized static ThreadPool getThreadPoolInstance() {
        if (sThreadPoolInstance == null) {
            Log.i(TAG, "[getThreadManagerInstance] New Instance");
            sThreadPoolInstance = new ThreadPool();
        }
        return sThreadPoolInstance;
    }
}

你有两种方法来调用你的 runnable 方法,使用 execute()submit()。它们之间的区别在于 submit() 返回一个 Future 对象,当从 Callable 回调返回对象 T 时,它允许你以编程方式取消正在运行的线程。你可以在这里阅读更多关于 Future信息