Android中的线程池详解

Android常见的线程池有四种,分别是FixThreadPool、CachedThreadPool、ScheduledThreadPool、SingleThreadExecutor。他们都是直接或间接通过配置ThreadPoolExecutor来实现自己的功能特性的。所以下面我们首先来介绍ThreadPoolExecutor这个类。

ThreadPoolExecutor

ThreadPoolExecutor的构造方法提供了一系列的参数来配置线程池,下面来介绍ThreadPoolExecutor的构造方法中各个参数的含义,这些参数会直接影响线程池的功能特性,下面是ThreadPoolExecutor的比较常用的构造方法。

public ThreadPoolExecutor(int corePoolSize,
                              int maximumPoolSize,
                              long keepAliveTime,
                              TimeUnit unit,
                              BlockingQueue<Runnable> workQueue,
                              ThreadFactory threadFactory)

corePoolSize
线程池的核心线程数,默认情况下,核心线程会在线程池一直存活,即使他们处于闲置状态。如果将ThreadPoolExecutor的allowCoreThreadTimeOut属性设置为true,那么闲置的核心线程在等待新任务到来时会有超时策略,这个时间间隔由keepAliveTime指定。超时核心线程就会被终止。

maximumPoolSize
线程池所容纳的最大线程数。活动线程数超过这个数字后,后续任务会被阻塞等待。

keepAliveTime
超时时长,超过这个时长,非核心线程就会被回收。如果将ThreadPoolExecutor的allowCoreThreadTimeOut属性设置为true,同样会作用于核心线程。

unit
用于指定keepAliveTime参数的时间单位。这是个枚举。常用有TimeUnit.MILLISECONDS(毫秒)、TimeUnit.SECONDS(秒)等。

workQueue
线程池的任务队列,通过线程池的execute方法提交的Runnable对象会存储在这个参数中。

threadFactory
线程工厂,为线程池提供创建新线程的功能。ThreadFactory是一个接口,它只有一个方法:Thread newThread(Runnable r)。

除了上面的主要参数外,还有一个不常用的参数RejectedExecutionHandler handler。当线程池无法执行新任务时,这可能是由于任务队列已满或者是无法执行任务,这个时候ThreadPoolExecutor会调用handler的rejectedExecution方法来通知调用者。默认情况下rejectedExecutor方法会直接抛出一个RejectedExecutionExecption。

ThreadPoolExecutor执行任务遵循如下规则:

(1)线程池线程数未到达核心线程数,就会直接启动一个核心线程来执行任务。
(2)线程池中的线程数达到或超过核心线程数,那么任务就会插入到任务队列中排队执行。
(3)如果在步骤2中无法将任务插入到任务队列中,这个时候线程数量未达到线程池最大值,那将启动一个非核心线程来执行任务。
(4) 如果步骤3中线程数量达到了线程池的最大值,那么会拒绝执行任务。会调用RejectedExecutionHandler的rejectedExecution方法来通知调用者。

接下来介绍android中四种常用的线程池

FixedThreadPool

通过Executors的newFixedThreadPool方法来创建。他是一种线程数量固定的线程池,且这些线程都是核心线程并且这些核心线程没有超时机制,另外任务队列也是没有大小限制的。当线程空闲时,它们都不会被回收,除非线程池被关闭。所以它能够很迅速的响应外界的请求。

public static ExecutorService newFixedThreadPool(int nThreads) {
        return new ThreadPoolExecutor(nThreads, nThreads,
                                      0L, TimeUnit.MILLISECONDS,
                                      new LinkedBlockingQueue<Runnable>());
    }

CachedThreadPool

通过Executors的newCachedThreadPool方法来创建。它只有非核心线程,且其最大线程数为Integer.MAX_VALUE。当线程池中线程都处于活动状态时,线程池会创建新的线程来处理新任务,线程中的空闲线程都有超时机制,这个超时机制为60秒。这类线程比较适合执行大量的耗时较少的任务。

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

ScheduledThreadPool

通过Executors的newScheduledThreadPool方法来创建。它的核心线程数量是固定的,非核心线程数没有限制,并且非核心线程闲置时会被立即回收,主要用于执行定时任务和具有固定周期的重复任务。

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

SingleThreadExecutor

通过Executors的newSingleThreadExecutor方法来创建。它只有一个核心线程,没有非核心线程。所有任务都在同一个线程中按顺序执行。

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

简单示例

下面是一个简单的线程池帮助类

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;


/**
 * TODO: 线程池工具类
 * 
 * @author liuxin
 * @date 2018-1-27 下午3:03:40
 * @version 0.1.0 
 */
public class ThreadUtils {
    private static final String TAG = "ThreadUtils";
    private static volatile ThreadUtils instance = null;

    // private constructor suppresses
    private ThreadUtils() {

    }

    public static ThreadUtils getInstance() {
        // if already inited, no need to get lock everytime
        if (instance == null) {
            synchronized (ThreadUtils.class) {
                if (instance == null) {
                    instance = new ThreadUtils();
                }
            }
        }

        return instance;
    }

    /**
     * 初始化的线程数,4个核心线程数
     */
    public ExecutorService threadPool = Executors.newFixedThreadPool(4);

    /**
     * 单一个核心线程
     */
    static ExecutorService singleThreadPool = Executors.newSingleThreadExecutor();

    /**
     * 执行延迟任务线程
     */
    public ScheduledExecutorService scheduleThreadPool = Executors.newScheduledThreadPool(2);

    /**
     * 立即执行任务
     * 
     * @param task ThreadUtils.getInstance().excute(run);
     */
    public void excute(Runnable task) {
        threadPool.execute(task);
    }

    /**
     * 单线程持操作,主要用于数据库的读写异步操作
     * 
     * @param task
     *            ThreadUtils.getInstance().excuteSingleThread(run);
     * @return 
     */
    public Future excuteSingleThread(Runnable task) {
        return singleThreadPool.submit(task);
    };

    /**
     * 延后执行任务
     * 
     * @param task
     * @param delay ThreadUtils.getInstance().schedule(run,1000);
     */
    public void schedule(Runnable task, long delay) {
        scheduleThreadPool.schedule(task, delay, TimeUnit.MILLISECONDS);
    }




    /**
     * @Title: shutdownThreadPool
     * @Description: TODO()
     * @return void 返回类型
     * 在onDestory ()中执行[ThreadUtils.getInstance().shutdownThreadPool()]
     */
    public void shutdownThreadPool() {
        threadPool.shutdownNow();
    }

    /**
     * @Title: shutdownThreadPool
     * @Description: TODO()
     * @return void 返回类型
     * 在onDestory ()中执行[ThreadUtils.getInstance().shutdownScheduleThreadPool()]
     */
    public void shutdownScheduleThreadPool() {
        scheduleThreadPool.shutdownNow();

    }

    /**
     * @Title: shutdownSingleThreadPool
     * @Description: TODO(单线程池销毁操作)
     * @return void 返回类型
     * 在onDestory()中执行[ThreadUtils.getInstance().shutdownSingleThreadPool()]
     */
    public  void shutdownSingleThreadPool() {
        singleThreadPool.shutdownNow();
    }   
}

还有个特殊需求,线程中返回结果,如

/**
*根据银行卡号获取哪个银行,在主线程调用即可
*@param context 上下文
*@param bank 银行卡号
*/
  private void getBank(final Context context, final String bank) {
        ExecutorService executorService = Executors.newSingleThreadExecutor();
        Future<String> future = executorService.submit(new Callable<String>() {

            @Override
            public String call() throws Exception {
                if (TextUtils.isEmpty(bank) || bank.length() < 6) {
                    return "";
                }
                String prefix = bank.substring(0, 6);
                String ppbank = "";
                InputStream inputStream = null;
                InputStreamReader inputStreamReader = null;
                try {
                    inputStream = context.getAssets().open("bank.json");
                    inputStreamReader = new InputStreamReader(inputStream, "utf-8");
                    Gson gson = new Gson();
                    List<Bank> banks = gson.fromJson(inputStreamReader, new TypeToken<List<Bank>>() {
                    }.getType());
                    if (banks != null && banks.size() > 0) {
                        for (int i = 0; i < banks.size(); i++) {
                            if (banks.get(i).getPrefix().equals(prefix)) {
                                ppbank = banks.get(i).getBank();
                                break;
                            }

                        }
                    }

                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    if (inputStreamReader != null) {
                        try {
                            inputStreamReader.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (inputStream != null) {
                        try {
                            inputStream.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
                return ppbank;
            }
        });
        try {

            String result = future.get();
            if (!TextUtils.isEmpty(result)) {
                etCardName.setText(result);
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
            future.cancel(true);
        } catch (ExecutionException e) {
            future.cancel(true);
            e.printStackTrace();
        } finally {
            executorService.shutdown();
        }

    }

后言

参考自《Android开发艺术探索》

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值