美文网首页
Android中线程池使用

Android中线程池使用

作者: 我想成为创业者 | 来源:发表于2018-11-01 15:08 被阅读0次

    为什么使用线程池

    1. 减少创建线程数量,提高APP性能 (减少创建和销毁线程的性能开销)
    2. 节省开销,防止并发线程过多,便于线程管理

    下面举例说明使用线程池的优势
    假如做一个新闻应用,ListView上有很多item,每个item上都有一张图片需要从网络上加载,如果不使用线程池,你可能通过thread来开启一个新线程:

            new Thread(new Runnable() {
                @Override
                public void run() {
                    //网络访问
                }
            }).start();
    

    new Thread()主要存在3点问题:
    1、每一个item都创建一个新线程会导致频繁的创建线程,线程执行完之后又被回收,又会导致频繁的GC
    2、 缺乏统一管理,各线程互相竞争,降低程序运行效率,手机页面卡顿,甚至会导致程序崩溃
    3、如果一个item滑出页面,则要停止该item上图片的加载,但是如果使用这种方式来创建线程,则无法实现线程停止执行

    如果使用线程池,我们就可以很好的解决以上问题
    1.重用已经创建好的线程,避免频繁创建进而导致的频繁GC
    2.控制线程并发数,合理使用系统资源,提高应用性能
    3.可以有效的控制线程的执行,比如定时执行,取消执行等

    ThreadPoolExecutor

    来看看ThreadPoolExecutor参数最多的构造方法(开发中用的更多的是5个参数的构造方法)

        public ThreadPoolExecutor(int corePoolSize,
                                  int maximumPoolSize,
                                  long keepAliveTime,
                                  TimeUnit unit,
                                  BlockingQueue<Runnable> workQueue,
                                  ThreadFactory threadFactory,
                                  RejectedExecutionHandler handler)
    
    1. corePoolSize线程池核心线程数量——值为Math.max(2, Math.min(CPU_COUNT - 1, 4),在2-4中间
    2. maximumPoolSize线程池最大线程数——值为CPU_COUNT * 2 + 1
    3. keepAliveTime非核心线程超时时长,当非核心线程闲置时间超过keepAliveTime后则会被回收。如果ThreadPoolExecutorallowCoreThreadTimeOut属性设置为true,则该参数也表示核心线程的超时时长
    4. unit
    5. workQueue线程池中任务队列,主要用来存储已被提交但尚未执行的任务。存储在这里的任务是由ThreadPoolExecutorexecute方法提交来的
    6. threadFactory为线程池提供创建新线程的功能
    7. handler拒绝策略,当线程无法执行新任务时(一般是由于线程池中的线程数量已经达到最大数或者线程池关闭导致的),默认情况下,当线程池无法处理新线程时会抛出一个RejectedExecutionException

    线程提交到线程池后运行规则

    1. execute一个线程之后,如果线程池中线程数未达核心线程数,则会立马启用一个核心线程去执行
    2. execute一个线程之后,如果线程池中线程数已经达到核心线程数,且workQueue未满,则将新线程放入workQueue中等待执行
    3. execute一个线程之后,如果线程池中线程数已经达到核心线程数但未超过非核心线程数,且workQueue已满,则开启一个非核心线程来执行任务
    4. execute一个线程之后,如果线程池中线程数已经超过非核心线程数,则拒绝执行该任务

    线程池的分类

    • FixedThreadPool
    • CachedThreadPool
    • ScheduledThreadPool
    • SingleThreadExecutor
    1. FixedThreadPool是核心线程数量固定的线程池
        public static ExecutorService newFixedThreadPool(int nThreads) {
            return new ThreadPoolExecutor(nThreads, nThreads,
                                          0L, TimeUnit.MILLISECONDS,
                                          new LinkedBlockingQueue<Runnable>());
        }
    

    上面代码看到核心线程数和最大线程数一样,说明在FixedThreadPool中没有非核心线程,所有的线程都是核心线程,且线程的超时时间为0,说明核心线程即使在没有任务可执行的时候也不会被销毁(这样可让FixedThreadPool更快速的响应请求),最后的线程队列是一个LinkedBlockingQueue,但是LinkedBlockingQueue却没有参数,这说明线程队列的大小为Integer.MAX_VALUE(2的31次方减1),所以FixedThreadPool的工作特点是当所有的核心线程都在执行任务的时候,新的任务只能进入线程队列中进行等待,直到有线程被空闲出来。

    1. SingleThreadExecutor
        public static ExecutorService newSingleThreadExecutor(ThreadFactory threadFactory) {
            return new FinalizableDelegatedExecutorService
                (new ThreadPoolExecutor(1, 1,
                                        0L, TimeUnit.MILLISECONDS,
                                        new LinkedBlockingQueue<Runnable>(),
                                        threadFactory));
        }
    

    从源码中可以看出singleThreadExecutorFixedThreadPool很像,不同的是SingleThreadExecutor核心线程数只有1,使用SingleThreadExecutor的最大好处就是可以避免我们去处理线程同步问题

    1. CachedThreadPool
        public static ExecutorService newCachedThreadPool(ThreadFactory threadFactory) {
            return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
                                          60L, TimeUnit.SECONDS,
                                          new SynchronousQueue<Runnable>(),
                                          threadFactory);
        }
    

    从源码可以看出CachedThreadPool是没有核心线程的,但是它的最大线程数却为Integer.MAX_VALUE,另外,它是有线程超时机制的,超时时间为60秒,这里它使用了SynchronousQueue作为线程队列,SynchronousQueue的特点上文已经说过了,这里不再赘述。CachedThreadPool特点:由于最大线程数为无限大,所以每当我们添加一个新任务进来的时候,如果线程池中有空闲的线程,则由该空闲的线程执行新任务,如果没有空闲线程,则创建新线程来执行任务。根据CachedThreadPool的特点,我们可以在有大量任务请求的时候使用CachedThreadPool,因为当CachedThreadPool中没有新任务的时候,它里边所有的线程都会因为超时而被终止。

    1. ScheduledThreadPool是一个具有定时定期执行任务功能的线程池
        public ScheduledThreadPoolExecutor(int corePoolSize) {
            super(corePoolSize, Integer.MAX_VALUE,
                  DEFAULT_KEEPALIVE_MILLIS, MILLISECONDS,
                  new DelayedWorkQueue());
        }
    

    从源码可以看出:它的核心线程数量是固定的,但是非核心线程是无穷大,当非核心线程闲置时,则会被立即回收。
    使用ScheduledThreadPool,我们可以通过如下几个方法来添加任务:

    • 延迟启动任务:
        public ScheduledFuture<?> schedule(Runnable command, long delay, TimeUnit unit);
    
    • 延迟定时执行任务:
        public ScheduledFuture<?> scheduleAtFixedRate(Runnable command, long initialDelay,
                                                      long period,TimeUnit unit);
    
    • 延迟执行任务
        public ScheduledFuture<?> scheduleWithFixedDelay(Runnable command,
                                                         long initialDelay,
                                                         long delay,
                                                         TimeUnit unit);
    

    参考

    相关文章

      网友评论

          本文标题:Android中线程池使用

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