定義一個新的 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資訊