1. 程式人生 > >Android Thread執行緒池管理類

Android Thread執行緒池管理類

package com.yunduan.parking.manager;

/**
 * author cowards
 * created on 2018\10\17 0017
 **/

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 1.  執行緒池管理類
 */
public class ThreadPoolManager {
    //1.將請求任務放到請求佇列中
    //通過阻塞式佇列來儲存任務
    private LinkedBlockingQueue<Runnable> queue = new LinkedBlockingQueue<>();

    //2.把佇列中的任務放到執行緒池
    private ThreadPoolExecutor threadPoolExecutor;

    private LinkedBlockingQueue<Runnable> removeTask = new LinkedBlockingQueue<>();

    //單例模式
    private static ThreadPoolManager singleInstance = new ThreadPoolManager();

    public static ThreadPoolManager getSingleInstance() {
        return singleInstance;
    }

    //私有化的構造方法
    private ThreadPoolManager() {
        threadPoolExecutor = new ThreadPoolExecutor(4, 20, 15, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(4), rejectedExecutionHandler);
        //執行執行緒池
        threadPoolExecutor.execute(runnable);
    }

    //新增任務
    public void execute(Runnable runnable) {
        if (runnable != null) {
            try {
                queue.put(runnable);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    //當執行緒數超過maxPoolSize或者keep-alive時間超時時執行拒絕策略
    private RejectedExecutionHandler rejectedExecutionHandler = new RejectedExecutionHandler() {
        /**
         * @param runnable 超時被執行緒池拋棄的執行緒
         * @param threadPoolExecutor
         */
        @Override
        public void rejectedExecution(Runnable runnable, ThreadPoolExecutor threadPoolExecutor) {
            //將該執行緒重新放入請求佇列中
            try {
                queue.put(runnable);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }
    };
    //3.讓他們開始工作起來
    //整個的工作執行緒
    private Runnable runnable = new Runnable() {
        @Override
        public void run() {
            while (true) {
                Runnable runnable = null;
                //不斷從從請求佇列中取出請求
                try {
                    runnable = queue.take();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                //如果不為空,放入執行緒池中執行
                if (runnable != null) {
                    if (!removeTask.contains(runnable)) {
                        threadPoolExecutor.execute(runnable);
                    }
                }
            }
        }
    };

    public void remove(Runnable runnable) {
        try {
            removeTask.put(runnable);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public void reset() {
        removeTask.clear();
        queue.clear();
    }
}