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

一、Android线程池介绍

1.1 原理

Android中的线程池概念来源于Java中的Executor,Executor是一个接口,真正的线程的实现为ThreadPoolExecutor。(ThreadPoolExecutor继承了AbstractExecutorService,AbstractExecutorService是ExecutorService的实现类,ExecutorService继承了Executor接口)。

1.2 分类

从线程池的功能特性上来说,Android中线程池主要分为4类:

  • FixedThreadPool(线程数量固定)、
  • CachedThreadPool(线程数量不定)、
  • ScheduledThreadPool(核心线程数量固定,非核心线程数量无限制)、
  • SingleThreadExecutor(只有一个核心线程,所有任务在里面按顺序执行)。

1.3 优点

  1. 重用线程池中的线程,避免频繁创建和销毁线程所带来的内存开销。
  2. 有效控制线程的最大并发数,避免因线程之间抢占资源而导致的阻塞现象。
  3. 能够对线程进行简单的管理,提供定时执行以及指定时间间隔循环执行等功能。

二、 Android线程池分类

由于Android中的线程池都是直接或间接通过配置ThreadPoolExecutor来实现的,因此在介绍它们之前要先介绍ThreadPoolExecutor。

2.1 ThreadPoolExecutor介绍

ThreadPoolExecutor有多个构造方法以及参数,下面介绍比较常用的构造方法。

    public ThreadPoolExecutor(int corePoolSize,
                              int maximumPoolSize,
                              long keepAliveTime,
                              TimeUnit unit,
                              BlockingQueue<Runnable> workQueue,
                              ThreadFactory threadFactory) {
        this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
             threadFactory, defaultHandler);
    }
  • corePoolSize:线程池的核心线程数,默认情况下核心线程会一直存活于线程池,即使处于闲置状态。如果设置了ThreadPoolExecutor里的allowCoreThreadTimeOut为True,则核心线程在等待新任务到来时会有超时终止策略。超时的时间间隔由keepAliveTime所决定。
    private volatile long keepAliveTime;
    private volatile boolean allowCoreThreadTimeOut;
  • maximumPoolSize:线程池所能容纳的最大线程数,当线程数达到这个数值后,后续的新任务将会被阻塞。
  • keepAliveTime:非核心线程超时时长,超过这个时间没有任务执行,非核心线程就会被回收。当核心线程设置allowCoreThreadTimeOut为true时,keepAliveTime同样作用于核心线程。
  • unit:用于指定keepAliveTime参数的时间单位,这是一个枚举
    ,常用的有TimeUnit.MILLISECONDS(毫秒)、TimeUnit.SECOUNDS(秒)以及TimeUnit.MINUTS(分钟)等,并且每个变量提供了转换函数方便各个单位数据的转换。
  • workQueue:线程池中的任务队列,通过线程池的execute方法提交的Runnable对象会存储在这个参数中。
  • threadFactory:线程工厂,为线程池提供创建新线程的功能。ThreadFactory是一个接口,它只有一个方法:Thread newThread(Runnable r);
  • handler:该handler的类型为RejectedExecutionHandler。这个参数不常用,它的作用是当线程池无法执行新任务时,会调用handler的rejectedExecution(Runnable r, ThreadPoolExecutor e)方法来抛出异常。无法执行的原因可能是由于队列满或者任务无法成功执行等。
    ThreadPoolExecutor执行任务大致遵循以下规则:
    (1)如果线程池中的线程数量未达到核心线程的数量,会直接启动一个核心线程来执行任务。
    (2)如果线程池中的线程数量已经达到或者超过核心线程的数量,那么任务会被插入到任务队列中排队等待执行。
    (3)如果第2步中无法插入新任务,说明任务队列已满,如果未达到规定的最大线程数量,则启动一个非核心线程来执行任务。
    (4)如果第3步中线程数量超过规定的最大值,则拒绝任务并使用RejectedExecutionHandler的rejectedExecution(Runnable r, ThreadPoolExecutor e)方法来通知调用者。

2.2 线程池的分类

先介绍一个类Executors,这个类定义了各种参数用于创建多种线程池,最终实现还是通过ThreadPoolExecutor类。
1. FixedThreadPool (Fixed:固定的,不变的)
通过Executors的newFixedThreadPool创建,通过创建时的参数可以看出又以下几个特点:

  • 线程数量固定且都是核心线程:核心线程数量和最大线程数量都是nThreads;
  • 都是核心线程且不会被回收,快速相应外界请求;
  • 没有超时机制,任务队列也没有大小限制;
  • 新任务使用核心线程处理,如果没有空闲的核心线程,则排队等待执行。
    public static ExecutorService newFixedThreadPool(int nThreads) {
        return new ThreadPoolExecutor(nThreads, nThreads,
                                      0L, TimeUnit.MILLISECONDS,
                                      new LinkedBlockingQueue<Runnable>());
    }

2. CachedThreadPool (Cached:缓存)
通过Executors的newCachedThreadPool创建,特点:

  • 线程数量不定,只有非核心线程,最大线程数任意大:传入核心线程数量的参数为0,最大线程数为Integer.MAX_VALUE;
  • 有新任务时使用空闲线程执行,没有空闲线程则创建新的线程来处理。
  • 该线程池的每个空闲线程都有超时机制,时常为60s(参数:60L, TimeUnit.SECONDS),空闲超过60s则回收空闲线程。
  • 适合执行大量的耗时较少的任务,当所有线程闲置超过60s都会被停止,所以这时几乎不占用系统资源。
    public static ExecutorService newCachedThreadPool() {
        return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
                                      60L, TimeUnit.SECONDS,
                                      new SynchronousQueue<Runnable>());
    }

3. ScheduledThreadPool(Scheduled:预定的、排定的)
通过Executors的newScheduledThreadPool创建,特点:

  • 核心线程数量固定,非核心线程数量无限制;
  • 非核心线程闲置超过10s会被回收;
  • 主要用于执行定时任务和具有固定周期的重复任务;
  • 四个里面唯一一个有延时执行和周期重复执行的功能:创建时
    ScheduledThreadPoolExecutor(corePoolSize)返回的是new ScheduledThreadPoolExecutor对象,ScheduledThreadPoolExecutor是ThreadPoolExecutor的子类,DelayedWorkQueue是ScheduledThreadPoolExecutor的一个静态内部类,主要用于处理任务队列延迟的工作。
    public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) {
        return new ScheduledThreadPoolExecutor(corePoolSize);
    }
    //默认闲置超时回收时常
    private static final long DEFAULT_KEEPALIVE_MILLIS = 10L;
    public ScheduledThreadPoolExecutor(int corePoolSize) {
        super(corePoolSize, Integer.MAX_VALUE,
              DEFAULT_KEEPALIVE_MILLIS, MILLISECONDS,
              new DelayedWorkQueue());
    }

4. SingleThreadExecutor (单线程线程池)
通过Executors的newSingleThreadExecutor创建,特点:

  • 只有一个核心线程,所有任务在同一个线程按顺序执行。
  • 所有的外界任务统一到一个线程中,所以不需要处理线程同步的问题。
    public static ExecutorService newSingleThreadExecutor() {
        return new FinalizableDelegatedExecutorService
            (new ThreadPoolExecutor(1, 1,
                                    0L, TimeUnit.MILLISECONDS,
                                    new LinkedBlockingQueue<Runnable>()));
    }

三、 Android线程池简单使用

3.1 线程池简单使用

(1)上面所说的四种常用线程池的实例化:

    //创建一个Runnable对象
    Runnable runnable = new Runnable() {
        @Override
        public void run() {
                // do something
        }
    };
    //四种线程池执行Runnable对象
    ExecutorService fixedThreadPool = Executors.newFixedThreadPool(1);
    fixedThreadPool.execute(runnable);
    
    ExecutorService cachedThreadPool = Executors.newCachedThreadPool();
    cachedThreadPool.execute(runnable);

    // 注意这里创建的是ScheduledExecutorService对象,ScheduledExecutorService是ExecutorService的子类
    ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(4);
    // 1000ms后执行runnable
    scheduledThreadPool.schedule(runnable,1000,TimeUnit.MILLISECONDS);
    // 1000ms后,每3000ms执行一次runnable
    scheduledThreadPool.scheduleAtFixedRate(runnable,1000,2000,TimeUnit.MILLISECONDS);
    isRunning = true;
    
    ExecutorService singleThreadExecutor = Executors.newSingleThreadExecutor();
    singleThreadExecutor.execute(runnable);

(2)简单使用小demo:
添加线程池开始执行和ScheduledThreadPool停止执行的两个按钮点击事件,布局就不贴了。

findViewById(R.id.btn_start).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            count = 0;
            mStatueText.setText("线程开始执行,次数:"+ count);
            startThreadPool();
        }
    });
findViewById(R.id.btn_stop).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if(null != scheduledThreadPool && isRunning){
                scheduledThreadPool.shutdown();
                mStatueText.setText("scheduledThreadPool线程停止,当前次数:"+ count);
                isRunning = false;
            }
        }
    });

startThreadPool();方法里Runnable每执行一次增加一次count并打到TextView上:

    Runnable runnable = new Runnable() {
        @Override
        public void run() {
                count++;
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mStatueText.setText("线程执行完毕,次数:"+ count);
                    }
                });
        }
    };

接着让所有的线程池执行这个Runnable对象,最后的结果是变量count的值从0直接到了3,然后又到5最后无限增长。
原因是除ScheduledThreadPool对象外的三个线程池很快执行了任务,ScheduledThreadPool对象的执行了两次任务,两个都延时1000ms。最后循环执行的任务一直在增加count的值。

相关文章:
Android多线程:理解和简单使用总结


转载:https://www.jianshu.com/p/ebdc3b3e136e
 

发布了49 篇原创文章 · 获赞 2 · 访问量 8585

猜你喜欢

转载自blog.csdn.net/yangjunjin/article/details/105030835