天天看點

Android開發線程池管理類之ThreadPoolExecutor工具類

平常開發中網絡請求自從Android4.0後強制要求放到子線程中避免主線程進行網絡請求,一般很多人習慣直接通過new Thread的方法。不建議這樣使用。我們用ThreadPoolExecutor線程池這個類建立比較好。是以有了下面的線程池工具類。

先來張JDK1.6的中文參數說明

Android開發線程池管理類之ThreadPoolExecutor工具類
package com.xiayiye.honorfirst.utils;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author xiayiye
 * 線程池工具
 */
public class ThreadUtils {
    /**
     * 根據cup核心數設定線程池數量
     */
    private static int corePoolSize = Runtime.getRuntime().availableProcessors();
    /**
     * 最大線程池數量= cpu核心數*2+1
     */
    private static int maximumPoolSize = corePoolSize * 2 + 1;
    /**
     * 等待線程的存活時間
     */
    private static long keepAliveTime = 1;
    /**
     * 等待線程存活時間的機關
     */
    private static TimeUnit unit = TimeUnit.HOURS;
    /**
     *
     */
    private static BlockingQueue<Runnable> workQueue = new LinkedBlockingQueue<>();
    /**
     * 預設的線程工廠
     */
    private static ThreadFactory threadFactory = Executors.defaultThreadFactory();
    /**
     * 取消政策,當超過等待線程池的數量後禁止添加了
     */
    private static RejectedExecutionHandler handler = new ThreadPoolExecutor.AbortPolicy();
    private static ThreadPoolExecutor executor;

    /**
     * 開啟線程池
     *
     * @param runnable runnable
     */
    public static void startThread(Runnable runnable) {
        executor = new ThreadPoolExecutor(
                corePoolSize,
                maximumPoolSize,
                keepAliveTime, unit,
                workQueue,
                threadFactory,
                handler);
        executor.execute(runnable);
    }

    /**
     * 取消線程池
     *
     * @param runnable runnable
     */
    public static void cancelThread(Runnable runnable) {
        if (null == runnable || executor == null) {
            return;
        }
        executor.remove(runnable);
    }
}
           

調用就更簡單了。

ThreadUtils.startThread(runnable);
ThreadUtils.cancelThread(runnable);
           

一個是開啟線程池,一個是取消線程池