android線程池的封裝工具類

整理下項目中遇到的輪子,後面做的時候直接方便移植

  1. android線程池工具類

線程池工具類

​ 主要用於後臺服務中一直輪詢的子線程,可以有效的管理線程的使用,再也不用new Thread().start()了

public class ThreadPoolManager
{
    private static final String TAG = "ThreadPoolManager";
    private ExecutorService mExecutorService; // 線程池對象

    /**
     * 類級的內部類,也就是靜態類的成員式內部類,該內部類的實例與外部類的實例
     * 沒有綁定關係,而且只有被調用時纔會裝載,從而實現了延遲加載
     */
    private static class ThreadPoolManagerHolder
    {
        /**
         * 靜態初始化器,由JVM來保證線程安全
         */
        private static ThreadPoolManager instance = new ThreadPoolManager();
    }

    /**
     * 私有化構造方法
     */
    private ThreadPoolManager()
    {
    }

    public static ThreadPoolManager getInstance()
    {
        return ThreadPoolManagerHolder.instance;
    }

    /**
     * 初始化線程池
     */
    public void initThreadPool()
    {
        if (mExecutorService == null)
        {
            mExecutorService = Executors.newCachedThreadPool();
        }
    }

    /**
     * 執行任務
     * @param runnable 任務
     */
    public void executeRunable(Runnable runnable)
    {
        try
        {
            if (mExecutorService != null && !mExecutorService.isShutdown())
            {
                mExecutorService.execute(runnable);
            }
        }
        catch (RejectedExecutionException e)
        {
            // 打印當前線程池中活躍的線程數量
            int threadCount = ((ThreadPoolExecutor) mExecutorService).getActiveCount();
            Log.d(TAG,
                    "[executeRunable]: current alive thread count = " + threadCount);
            e.printStackTrace();
        }
    }

    /**
     * 關閉線程池
     */
    public void shutdownExecutor()
    {
        if (mExecutorService != null && !mExecutorService.isShutdown())
        {
            mExecutorService.shutdown();
            mExecutorService = null;
        }
    }
}

使用方法

  	/**
     * 初始化更新線程
     */
    public void initUpdateRunnable() {
        ThreadPoolManager.getInstance().initThreadPool();

        ThreadPoolManager.getInstance().executeRunable(new Runnable() {
            @Override
            public void run() {
                // dos somethings
            }
        });
    }


// 關閉整個線程池
ThreadPoolManager.getInstance().shutdownExecutor();

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章