Android 中的线程池

来源:互联网 发布:数据库模型分为哪三种 编辑:程序博客网 时间:2024/06/05 17:53

线程池的优点

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

ThreadPoolExecutor

一个比较常用的构造方法

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

corePoolSize:核心线程数
maximumPoolSize:最大线程数
keepAliveTime:超时时长
unit:keepAliveTime 参数的时间单位
workQueue:任务队列
threadFactory:线程工厂

ThreadPoolExecutor 执行任务时遵循如下规则:
1. 线程池中的线程数量 < 核心线程数,启动一个核心线程执行任务;
2. 核心线程数 <= 线程池中的线程数量 < 最大线程数 && 任务队列未满,将任务插入到任务队列排队等待执行;
3. 核心线程数 <= 线程池中的线程数量 < 最大线程数 && 任务队列已满,启动一个非核心线程执行任务;
4. 线程池中的线程数量 = 最大线程数,拒绝执行此任务,ThreadPoolExecutor 调用 RejectedExecutionHandler 的 rejectedExecution 方法通知调用者

具体的线程池

AsyncTask

规格:
核心线程数等于 CPU 核心数 + 1
最大线程数等于 CPU 核心数 * 2 + 1
核心线程无超时机制,非核心线程在闲置时的超时时间为1秒
任务队列的容量为128

FixedThreadPool

规格:
线程数量固定,只有核心线程
线程没有超时机制,不会被回收
任务队列没有大小限制

特点:
能够更加快速地响应外界的请求

CachedThreadPool

规格:
最大线程数可以任意大,只有非核心线程
线程有超时机制,超时时长为60秒
任务队列无法存储任务,导致任何任务都会立即被执行

特点:
适合执行大量的耗时较少的任务

ScheduledThreadPool

规格:
核心线程数量固定,非核心线程数没有限制
当非核心线程闲置时会被立即回收

特点:
主要用于执行定时任务和具有固定周期的重复任务

SingleThreadExecutor

规格:
只有一个核心线程,没有非核心线程

特点:
确保所有的任务都在同一个线程中按顺序执行,使得在这些任务之间不需要处理线程同步的问题

4种线程池的典型使用方法

Runnable command = new Runnable() {    @Override    public void run() {        Log.d("Guu", "start command!");    }};ExecutorService fixedThreadPool = Executors.newFixedThreadPool(4);fixedThreadPool.execute(command);ExecutorService cachedThreadPool = Executors.newCachedThreadPool();cachedThreadPool.execute(command);ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(4);// 2000 ms 后执行 commandscheduledThreadPool.schedule(command, 2000, TimeUnit.MILLISECONDS);// 延迟 10 ms 后,每隔 1000 ms 执行一次 commandscheduledThreadPool.scheduleAtFixedRate(command, 10, 1000, TimeUnit.MILLISECONDS);ExecutorService singleThreadExecutor = Executors.newSingleThreadExecutor();singleThreadExecutor.execute(command);

实际应用中,可以根据实际需要灵活地配置线程池。

原创粉丝点击