工具篇——ThreadPoolUtil(用於進行線程的管理,防止重複創建、殺死線程)

代碼如下:

package com.wy.test.other;

import android.support.annotation.NonNull;

import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 線程池的工具類
 * 用於進行線程的管理,防止重複創建、殺死線程。
 * <p>
 * 多線程運行期間,如果系統不斷的創建、殺死新線程,
 * 會產生過度消耗系統資源,以及過度切換線程的問題,甚至可能導致系統資源的崩潰。
 * 因此需要線程池,對線程進行管理。
 */
public class ThreadPoolUtil {

    private String TAG = getClass().getName();
    private static volatile ThreadPoolUtil mInstance;
    //核心線程池的數量,同時能夠執行的線程數量
    private int corePoolSize;
    //最大線程池數量,表示當緩衝隊列滿的時候能繼續容納的等待任務的數量
    private int maxPoolSize;
    //存活時間
    private long keepAliveTime = 1;
    private TimeUnit unit = TimeUnit.HOURS;
    private ThreadPoolExecutor executor;

    private ThreadPoolUtil() {
        //給corePoolSize賦值:當前設備可用處理器核心數*2 + 1,能夠讓cpu的效率得到最大程度執行(有研究論證的)
        corePoolSize = Runtime.getRuntime().availableProcessors() * 2 + 1;
        maxPoolSize = corePoolSize;
        executor = new ThreadPoolExecutor(
                //當某個核心任務執行完畢,會依次從緩衝隊列中取出等待任務
                corePoolSize,
                // 然後new LinkedBlockingQueue<Runnable>(),然後maximumPoolSize,但是它的數量是包含了corePoolSize的
                maxPoolSize,
                //表示的是maximumPoolSize當中等待任務的存活時間
                keepAliveTime,
                unit,
                //緩衝隊列,用於存放等待任務,Linked的先進先出
                new LinkedBlockingQueue<Runnable>(),
                new DefaultThreadFactory(Thread.NORM_PRIORITY, "thread-pool-"),
                new ThreadPoolExecutor.AbortPolicy()
        );
    }

    public static ThreadPoolUtil getInstance() {
        if (mInstance == null) {
            synchronized (ThreadPoolUtil.class) {
                if (mInstance == null) {
                    mInstance = new ThreadPoolUtil();
                }
            }
        }
        return mInstance;
    }

    /**
     * 執行任務
     *
     * @param runnable
     */
    public void execute(Runnable runnable) {
        if (executor == null) {
            executor = new ThreadPoolExecutor(
                    corePoolSize,
                    maxPoolSize,
                    keepAliveTime,
                    TimeUnit.SECONDS,
                    new LinkedBlockingQueue<Runnable>(),
                    new DefaultThreadFactory(Thread.NORM_PRIORITY, "thread-pool-"),
                    new ThreadPoolExecutor.AbortPolicy());
        }
        if (runnable != null) {
            executor.execute(runnable);
        }
    }

    /**
     * 移除任務
     *
     * @param runnable
     */
    public void remove(Runnable runnable) {
        if (runnable != null) {
            executor.remove(runnable);
        }
    }

    private static class DefaultThreadFactory implements ThreadFactory {

        //線程池的計數
        private static final AtomicInteger poolNumber = new AtomicInteger(1);
        //線程的計數
        private final AtomicInteger threadNumber = new AtomicInteger(1);
        private final ThreadGroup group;
        private final String namePrefix;
        private final int threadPriority;

        DefaultThreadFactory(int threadPriority, String threadNamePrefix) {
            this.threadPriority = threadPriority;
            this.group = Thread.currentThread().getThreadGroup();
            this.namePrefix = threadNamePrefix + poolNumber.getAndIncrement() + "-thread-";
        }

        @Override
        public Thread newThread(@NonNull Runnable r) {
            Thread thread = new Thread(group, r, namePrefix + threadNumber.getAndIncrement(), 0);
            // 返回True該線程就是守護線程
            // 守護線程應該永遠不去訪問固有資源,如:數據庫、文件等。因爲它會在任何時候甚至在一個操作的中間發生中斷。
            if (thread.isDaemon()) {
                thread.setDaemon(false);
            }
            thread.setPriority(threadPriority);
            return thread;
        }
    }
}

在項目中的應用:

//使用線程池工具處理耗時操作
ThreadPoolUtil.getInstance().execute(new Runnable() {
    @Override
    public void run() {
         //在此執行耗時操作
         //例如:文件下載、數據庫存取、音頻格式轉換等
    }
});

 

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