Android 線程池

在使用線程處理異步任務時,若是每次執行任務都去建立線程執行完成任務又銷燬線程,因爲建立線程和銷燬線程會須要一些CPU資源,因此咱們不得不使用線程池管理線程。java

####ThreadPollExecutor多線程

ThreadPoolExecutor是建立一個線程池的類,它有四個構造方法,咱們看參數最多的那個:app

public ThreadPoolExecutor(int corePoolSize,
                          int maximumPoolSize,
                          long keepAliveTime,
                          TimeUnit unit,
                          BlockingQueue<Runnable> workQueue,
                          ThreadFactory threadFactory,
                          RejectedExecutionHandler handler) {
    if (corePoolSize < 0 ||
        maximumPoolSize <= 0 ||
        maximumPoolSize < corePoolSize ||
        keepAliveTime < 0)
        throw new IllegalArgumentException();
    if (workQueue == null || threadFactory == null || handler == null)
        throw new NullPointerException();

    this.corePoolSize = corePoolSize;
    this.maximumPoolSize = maximumPoolSize;
    this.workQueue = workQueue;
    this.keepAliveTime = unit.toNanos(keepAliveTime);
    this.threadFactory = threadFactory;
    this.handler = handler;
}
複製代碼

解釋一些這些參數的做用:異步

  • corePoolSize:核心線程數,默認狀況下線程池是空的,只有在提交任務時纔會建立線程。 在提交任務時會判斷,若是當前運行的線程數少於corePoolSize,則會建立新的線程來處理這個任務,若是等於或多於corePoolSize,則不會建立線程,而是將任務加入任務隊列等待執行,那若是任務隊列滿了而且線程池的線程數量小於maximumPoolSize ,那麼會建立線程執行任務,若是隊列滿了而且線程池的線程數量大於等於maximumPoolSize,那麼會執行飽和策略。有一個彩蛋,若是你想提早啓動線程池中的核心線程,你只要調用prestartAllCoreThread方法,啓動全部的核心線程,固然還有prestartCoreThread方法啓動一個。ide

  • maximumPoolSize :線程池容許建立最大的線程數。若是池中線程等於corePoolSize,而且任務隊列也滿了,那麼會建立新的線程執行任務,前提是池中的線程數小於maximumPoolSize 。oop

  • keepAliveTime :非核心線程閒置的超時時間,超過這個時間那麼閒置的線程將被回收,unit是時間單位。post

  • workQueue:任務隊列,當前執行任務的線程數大於corePoolSize時,那麼後來的任務將被加入workQueue。this

*threadFactory:線程工廠,建立線程用的;spa

  • RejectedExecutionHandler :飽和策略,這是當任務隊列滿了和當前執行任務的線程數大於等於maximumPoolSize 時即線程池滿了,所採起的的策略,以供有四種策略: 一、CallerRunsPolicy:使用調用者當前的線程來處理任務; 二、DiscardPolicy:不執行該任務,並將該任務刪除; 三、DiscardOldestPolicy:丟棄隊列最近的任務,並執行當前的任務; 四、AbortPolicy:這是默認策略,表示沒法執行任務,並拋出RejectedExecutionException異常。

看一下執行邏輯圖: 線程

線程池執行過程.png

####沒有代碼,一切都是紙老虎

public class ThreadDemo {
//表示執行飽和策略時退出不在執行任務
static boolean isBreak = false;

public static void main(String[] args) throws ExecutionException, InterruptedException {
    //建立線程池
    ThreadPoolExecutor executor =
            new ThreadPoolExecutor(5, 8, 60, TimeUnit.SECONDS,
                    new LinkedBlockingDeque<>(10), new RejectedExecutionHandler() {
                @Override
                public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
                    System.out.println("飽和策略" + r);
                    isBreak = true;
                }
            });

    while (!isBreak) {
        System.out.println("核心線程數: " + executor.getCorePoolSize()
                + ", 線程池最大線程數: " + executor.getMaximumPoolSize()
                + ", 當前線程數: " + executor.getPoolSize()
                + ", 任務隊列大小 " + executor.getQueue().size());

        TimeUnit.MILLISECONDS.sleep(1000);
        executor.execute(() -> {
            try {
                TimeUnit.SECONDS.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
    }
}
複製代碼

}

最後輸出的日誌:

核心線程數: 3, 線程池最大線程數: 5, 當前線程數: 0, 任務隊列大小 0
核心線程數: 3, 線程池最大線程數: 5, 當前線程數: 1, 任務隊列大小 0
核心線程數: 3, 線程池最大線程數: 5, 當前線程數: 2, 任務隊列大小 0
核心線程數: 3, 線程池最大線程數: 5, 當前線程數: 3, 任務隊列大小 0
核心線程數: 3, 線程池最大線程數: 5, 當前線程數: 3, 任務隊列大小 1
核心線程數: 3, 線程池最大線程數: 5, 當前線程數: 3, 任務隊列大小 2
核心線程數: 3, 線程池最大線程數: 5, 當前線程數: 3, 任務隊列大小 3
核心線程數: 3, 線程池最大線程數: 5, 當前線程數: 4, 任務隊列大小 3
核心線程數: 3, 線程池最大線程數: 5, 當前線程數: 5, 任務隊列大小 3
飽和策略RejectedExecutionException
複製代碼

在提交任務時會判斷,若是當前執行任務的線程數少於corePoolSize,會建立新的線程來處理該任務,若是等於或多於corePoolSize,則不會建立線程,而是將該任務加入任務隊列等待執行,那若是任務隊列滿了而且線程池的線程數量小於maximumPoolSize ,那麼會建立非核心線程執行該任務,若是隊列滿了而且線程池的線程數量大於等於maximumPoolSize,那麼會執行飽和策略。

在java中還給咱們提供四種線程池,分別是:FixedThreadPoll、CachedThreadPool、SingleThreadPool和ScheduledThreadPool,這四種線程池,無非就是經過ThreadPoolExecutor的不一樣配置建立出來,具體這四中的實現想了解能夠去看一下。

最後附上本身寫的SimpleEventBus時封裝的的線程池代碼:

/**
   * 線程切換
 */
public class ScheduleRouterExecutor extends ThreadPoolExecutor {
//主線程
private final Handler mainHandler = new Handler(Looper.getMainLooper());
//CPU數量
private static final int CPU_COUNT = Runtime.getRuntime().availableProcessors();
//核心線程數量
private static final int INIT_THREAD_COUNT = CPU_COUNT + 1;
//線程池最大縣城內容量
private static final int MAX_THREAD_COUNT = INIT_THREAD_COUNT * 2;
//非核心線程閒置存活的時間(秒)
private static final long SURPLUS_THREAD_LIFE = 30L;

//默認線程工廠
private static ThreadFactory DEFAULT_THREAD_FACTORY = new DefaultThreadFactory();

private static RejectedExecutionHandler REJECTED_HANDLER = new RejectedExecutionHandler() {
    @Override
    public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
        Log.e("tag", "提交的任務太多了哥們 ,已經執行飽和策略!");
    }
};

private static ScheduleRouterExecutor instance;

@NonNull
public static ScheduleRouterExecutor getInstance() {
    if (null == instance) {
        synchronized (ScheduleRouterExecutor.class) {
            if (null == instance) {
                instance = new ScheduleRouterExecutor(INIT_THREAD_COUNT, MAX_THREAD_COUNT,
                        SURPLUS_THREAD_LIFE, TimeUnit.SECONDS,
                        new LinkedBlockingQueue<Runnable>(64),
                        DEFAULT_THREAD_FACTORY,
                        REJECTED_HANDLER);
            }
        }
    }
    return instance;
}


private ScheduleRouterExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit,
                               BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory,
                               RejectedExecutionHandler handler) {
    super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory, handler);
}


public void executeTask(@NonNull EventTask task) {
    if (task.getThreadMode() == ThreadMode.BACKGROUND) {
        if (Looper.myLooper() == Looper.getMainLooper()) {
            execute(task);
            return;
        }
        task.run();
    } else if (task.threadMode == ThreadMode.MAIN) {
        if (Looper.myLooper() != Looper.getMainLooper()) {
            mainHandler.post(task);
        } else {
            task.run();
        }
    }
}


/**
 * 線程執行結束,檢查是否存在的異常
 *
 * @param r the runnable that has completed
 * @param t the exception that caused termination, or null if
 */
@Override
protected void afterExecute(Runnable r, Throwable t) {
    super.afterExecute(r, t);
    Log.e("tag", "afterExecute");
    if (t == null && r instanceof Future<?>) {
        try {
            ((Future<?>) r).get();
        } catch (CancellationException ce) {
            t = ce;
        } catch (ExecutionException ee) {
            t = ee.getCause();
        } catch (InterruptedException ie) {
            // ignore/reset
            Thread.currentThread().interrupt();
        }
    }
    if (t != null) {
        Log.e("tag", "Running task appeared exception! Thread [" +
                Thread.currentThread().getName() + "], because [" + t.getMessage() + "]\n" +
              Arrays.toString(t.getStackTrace()));
        }
    }
}
複製代碼

線程工廠:

/**
   * 線程池工廠類
   */
public class DefaultThreadFactory implements ThreadFactory {

//統計線程池的數量
private static final AtomicInteger poolNumber = new AtomicInteger(1);
//統計當前線程池的線程數量
private final AtomicInteger threadNumber = new AtomicInteger(1);
private final ThreadGroup threadGroup;
private final String namePrefix;

public DefaultThreadFactory() {
    SecurityManager securityManager = System.getSecurityManager();
    threadGroup = (securityManager != null) ? securityManager.getThreadGroup() :
            Thread.currentThread().getThreadGroup();
    namePrefix = "Simple EventBus task pool No." + poolNumber.getAndIncrement() + ", thread No.";
}

@Override
public Thread newThread(@NonNull Runnable runnable) {
    String threadName = namePrefix + threadNumber.getAndIncrement();


    Log.e("tag", "Thread production, name is [" + threadName + "]");

    final Thread thread = new Thread(threadGroup, runnable, threadName, 0);

    if (thread.isDaemon()) {//設置爲非後臺線程
        thread.setDaemon(false);
    }


    if (thread.getPriority() != Thread.NORM_PRIORITY) {//優先級爲normal
        thread.setPriority(Thread.NORM_PRIORITY);
    }


    // 捕獲多線程處理中的異常
    thread.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
        @Override
        public void uncaughtException(Thread thread, Throwable ex) {
            Log.e("tag", "Running task appeared exception! Thread [" + thread.getName() + "], because [" + ex.getMessage() + "]");
        }
    });
    return thread;
}
}
複製代碼
相關文章
相關標籤/搜索