Android中的线程池

线程池有以下的优点:

  • 重用线程池中的线程,避免因为线程的创建和销毁所带来的性能上的开销
  • 能有效控制线程池的最大并发数,避免大量的线程之间因为互相抢占系统资源而导致阻塞现象
  • 能够对线程池就行简单的管理,并提供定时执行以及指定间隔循环
线程池介绍

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);
    }

ThreadPoolExecutor执行任务是遵循的规则


image.png

参数设置

private static final int CPU_COUNT = Runtime.getRuntime().availableProcessors();
    private static final int CORE_POOL_SIZE = CPU_COUNT + 1;
    private static final int MAXIMUM_POOL_SIZE = CPU_COUNT * 2 + 1;
    private static final int KEEP_ALIVE = 1;

    private static final ThreadFactory sThreadFactory = new ThreadFactory() {
        private final AtomicInteger mCount = new AtomicInteger(1);

        public Thread newThread(Runnable r) {
            return new Thread(r, "AsyncTask #" + mCount.getAndIncrement());
        }
    };

    private static final BlockingQueue<Runnable> sPoolWorkQueue =
            new LinkedBlockingQueue<Runnable>(128);

    /**
     * An {@link Executor} that can be used to execute tasks in parallel.
     */
    public static final Executor THREAD_POOL_EXECUTOR
            = new ThreadPoolExecutor(CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE,
                    TimeUnit.SECONDS, sPoolWorkQueue, sThreadFactory);

线程池的分类

·FixedThreadPool:
数量固定的核心线程池,没有超时机制。任务队列大小没有限制。
·CachedThreadPool:
线程数量不定,只有非核心贤臣,最大线程数位Integer.MAX_VALUE。它比较适合执行大量的耗时较少的任务
·ScheduledThreadPool:
核心线程数量固定,非核心线程数量没有限制。适合执行定时任务和具有固定周期的重复任务。
·SingleThreadExecutor:
只有一个核心线程

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 线程池的优点: 重用线程池中的线程,避免因为线程的创建和销毁带来的性能消耗 能有效的控制线程的最大并发数,避免大量...
    乆丩乣阅读 5,415评论 5 30
  • 很久没有更新了,首先跟各位说声对不起。近段时间陷进了失眠的深渊难以自拔,工作、生活一团糟,每天都是满满的负能量,学...
    山野纸鹤阅读 1,098评论 0 9
  • 线程池的好处 (1)重用线程池中的线程,避免因为线程的创建和销毁所带来的性能的开销。(2)能有效控制线程池的最大并...
    蓝枫zeke阅读 359评论 0 2
  • Android 中的四种线程池 在开发中使用线程池的优点 重用线程池中的线程,避免因为线程的创建和销毁带来的性能开...
    任教主来也阅读 193评论 0 0
  • 猝不及防,史上首次一条政治新闻引发起姐妹界的疯转,标题是:“杀害金正男特工身份曝光,疑似1988年中年女子”。 原...
    魏费斯阅读 1,450评论 15 4