美文网首页Anmdroid难点解答
11.3 Android中的线程池

11.3 Android中的线程池

作者: 詹徐照 | 来源:发表于2018-03-26 08:34 被阅读7次

线程池优点:

  1. 重用线程,避免创建、销毁线程的开销;
  2. 有效控制线程最大并发数,避免大量线程之间相互抢占系统资源而导致的阻塞现象。
  3. 能够对线程进行简单管理,并提供定时执行和循环执行等功能。
interface Executor
class ThreadPoolExecutor implements Executor;

11.3.1 ThreadPoolExecutor

构造方法

    /**
     * Creates a new {@code ThreadPoolExecutor} with the given initial
     * parameters and default rejected execution handler.
     *
     * @param corePoolSize the number of threads to keep in the pool, even
     *        if they are idle, unless {@code allowCoreThreadTimeOut} is set
     * @param maximumPoolSize the maximum number of threads to allow in the
     *        pool
     * @param keepAliveTime when the number of threads is greater than
     *        the core, this is the maximum time that excess idle threads
     *        will wait for new tasks before terminating.
     * @param unit the time unit for the {@code keepAliveTime} argument
     * @param workQueue the queue to use for holding tasks before they are
     *        executed.  This queue will hold only the {@code Runnable}
     *        tasks submitted by the {@code execute} method.
     * @param threadFactory the factory to use when the executor
     *        creates a new thread
     * @throws IllegalArgumentException if one of the following holds:<br>
     *         {@code corePoolSize < 0}<br>
     *         {@code keepAliveTime < 0}<br>
     *         {@code maximumPoolSize <= 0}<br>
     *         {@code maximumPoolSize < corePoolSize}
     * @throws NullPointerException if {@code workQueue}
     *         or {@code threadFactory} is null
     */
    public ThreadPoolExecutor(int corePoolSize,
                              int maximumPoolSize,
                              long keepAliveTime,
                              TimeUnit unit,
                              BlockingQueue<Runnable> workQueue,
                              ThreadFactory threadFactory) {
        this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
             threadFactory, defaultHandler);
    }

corePoolSize

 * When a new task is submitted in method {@link #execute(Runnable)},
 * and fewer than corePoolSize threads are running, a new thread is
 * created to handle the request, even if other worker threads are
 * idle.  If there are more than corePoolSize but less than
 * maximumPoolSize threads running, a new thread will be created only
 * if the queue is full. 

maximumPoolSize
keepAliveTime
unit
workQueue
threadFactory

11.3.2 线程池分类

Executors可以方便的产生下面几种线程池。

  1. FixedThreadPool
    核心线程开启后,不会被回收,能够更加快速的响应外界请求。
    public static ExecutorService newFixedThreadPool(int nThreads) {
        return new ThreadPoolExecutor(nThreads, nThreads,
                                      0L, TimeUnit.MILLISECONDS,
                                      new LinkedBlockingQueue<Runnable>());
    }
  1. CachedThreadPool
    适合执行大量的耗时较少的任务。
    当整个线程池都处于闲置状态时,几乎不占用系统资源。
    public static ExecutorService newCachedThreadPool() {
        return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
                                      60L, TimeUnit.SECONDS,
                                      new SynchronousQueue<Runnable>());
    }
  1. ScheduledThreadPool
    核心线程数固定,非核心线程数没有限制。
    适合执行定时任务或固定周期的重复任务。
    public ScheduledThreadPoolExecutor(int corePoolSize) {
        super(corePoolSize, Integer.MAX_VALUE,
              DEFAULT_KEEPALIVE_MILLIS, MILLISECONDS,
              new DelayedWorkQueue());
    }
  1. SingleThreadExecutor
    public static ExecutorService newSingleThreadExecutor() {
        return new FinalizableDelegatedExecutorService
            (new ThreadPoolExecutor(1, 1,
                                    0L, TimeUnit.MILLISECONDS,
                                    new LinkedBlockingQueue<Runnable>()));
    }

类关系图

image.png
@startuml
@startuml
package Hierarchy <<Rectangle>> {
  interface Executor
  interface ExecutorService
  abstract class AbstractExecutorService
  class ThreadPoolExecutor
}

class Executors {
  + ExecutorService newFixedThreadPool()
  + ExecutorService newSingleThreadExecutor()
  + ExecutorService newCachedThreadPool()
  + ExecutorService newScheduledThreadPool()
}

Executor <-- ExecutorService: extends
ExecutorService <-- AbstractExecutorService: implements
AbstractExecutorService <-- ThreadPoolExecutor  : extends

Executors --> ThreadPoolExecutor: depend on
Executors --> ExecutorService: create
@enduml

相关文章

  • 11.3 Android中的线程池

    线程池优点: 重用线程,避免创建、销毁线程的开销; 有效控制线程最大并发数,避免大量线程之间相互抢占系统资源而导致...

  • Android线程池的使用

    一、线程与线程池,为什么要使用线程池 1、Android中的线程 在Android中有主线程和子线程的区分。主线程...

  • Android 多线程:线程池理解和使用总结

    一、Android线程池介绍 1.1 原理 Android中的线程池概念来源于Java中的Executor,Exe...

  • 19. 线程池

    Android 中的线程池就是 java 中的线程池,即 ThreadPoolExecutor 类。 Java 通...

  • 线程池

    话题:线程池Android中的线程池有哪些?它们的区别是什么?为什么要使用线程池? 线程是Android里面一个很...

  • Android 多线程

    AsyncTaskHandlerThreadIntentServiceandroid中的线程池 android 中...

  • 笔记:Android线程和线程池

    Android线程和线程池 Android中的线程操作相关的类有 AsyncTask IntentService ...

  • Android面试之线程和线程池

    Android中的线程形态 AsyncTask底层用到了线程池。AsyncTask封装了线程池和Handler,它...

  • 第十九周 线程池

    话题:线程池 Android 中的线程池有哪些?它们的区别是什么?为什么要使用线程池?关键字:线程池、Thread...

  • 线程池创建和相关知识

    线程池创建(单例):Android线程池得要这么用 - 简书 线程池相关知识:Android开发之线程池使用总结 ...

网友评论

    本文标题:11.3 Android中的线程池

    本文链接:https://www.haomeiwen.com/subject/boslcftx.html