1. 程式人生 > >管理android執行緒池

管理android執行緒池

public class ThreadManager {
    private ThreadManager() {

    }

    private static ThreadManager instance = new ThreadManager();
    private ThreadPoolProxy longPool;
    private ThreadPoolProxy shortPool;

    public static ThreadManager getInstance() {
        return instance;
    }

    // 聯網比較耗時
// cpu的核數*2+1 public synchronized ThreadPoolProxy createLongPool() { if (longPool == null) { longPool = new ThreadPoolProxy(5, 5, 5000L); } return longPool; } // 操作本地檔案 public synchronized ThreadPoolProxy createShortPool() { if(shortPool==null
){ shortPool = new ThreadPoolProxy(3, 3, 5000L); } return shortPool; } public class ThreadPoolProxy { private ThreadPoolExecutor pool; private int corePoolSize; private int maximumPoolSize; private long time; public ThreadPoolProxy
(int corePoolSize, int maximumPoolSize, long time) { this.corePoolSize = corePoolSize; this.maximumPoolSize = maximumPoolSize; this.time = time; } /** * 執行任務 * @param runnable */ public void execute(Runnable runnable) { if (pool == null) { // 建立執行緒池 /* * 1. 執行緒池裡面管理多少個執行緒2. 如果排隊滿了, 額外的開的執行緒數3. 如果執行緒池沒有要執行的任務 存活多久4. * 時間的單位 5 如果 執行緒池裡管理的執行緒都已經用了,剩下的任務 臨時存到LinkedBlockingQueue物件中 排隊 */ pool = new ThreadPoolExecutor(corePoolSize, maximumPoolSize, time, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>(10)); } pool.execute(runnable); // 呼叫執行緒池 執行非同步任務 } /** * 取消任務 * @param runnable */ public void cancel(Runnable runnable) { if (pool != null && !pool.isShutdown() && !pool.isTerminated()) { pool.remove(runnable); // 取消非同步任務 } } } }

呼叫:

ThreadManager.getInstance().createLongPool().execute(new Runnable() {

            @Override
            public void run() {
                SystemClock.sleep(2000);    
            }
        });