Android 线程介绍(二)—— 常用线程池介绍

本文介绍了Android线程池的核心参数,包括核心线程数、最大线程数、超时时间等,并详细讲解了四种常用线程池:FixedThreadPool、CachedThreadPool、ScheduledThreadPool和SingleThreadPool的特点与应用场景。特别指出,由于特定线程池可能导致内存消耗过大,如设置不当,可能会引起OOM错误,因此在使用时需谨慎选择。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

线程池创建参数介绍:

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

corePoolSize: 线程池中核心线程的数量。
maximumPoolSize:线程池中最大线程数量。
keepAliveTime:非核心线程的超时时长,当系统中非核心线程闲置时间超过keepAliveTime之后,则会被回收。如果ThreadPoolExecutor的allowCoreThreadTimeOut属性设置为true,则该参数也表示核心线程的超时时长。
unit:keepAliveTime这个参数的单位,有纳秒、微秒、毫秒、秒、分、时、天等。
workQueue:线程池中的任务队列,该队列主要用来存储已经被提交但是尚未执行的任务。存储在这里的任务是由ThreadPoolExecutor的execute方法提交来的。
threadFactory:为线程池提供创建新线程的功能,这个我们一般使用默认即可。
handler: 拒绝策略,当线程无法执行新任务时(一般是由于线程池中的线程数量已经达到最大数或者线程池关闭导致的),默认情况下,当线程池无法处理新线程时,会抛出一个RejectedExecutionException。

四种常见的线程池:
FixedThreadPool:

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

数量固定的线程池,核心线程数等于最大线程数,即只有核心线程。
CachedThreadPool

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

没有核心线程,只有非核心线程,最大线程数量是Integer.MAX_VALUE,实际就是代表非核心线程数量任意大。任务队列是一个空集合,表示任何任务都会被立即执行。
这类线程池适合执行大量的耗时少的任务。
但是存在一个问题:线程太多会占用内存资源,导致OOM,所以不建议使用

ScheduledThreadPool

public ScheduledThreadPoolExecutor(int corePoolSize) {
    super(corePoolSize, Integer.MAX_VALUE,
          DEFAULT_KEEPALIVE_MILLIS, MILLISECONDS,
          new DelayedWorkQueue());
}

核心线程数是固定的,非核心线程数量没有限制,是Integer.MAX_VALUE。这类线程池主要用于执行定时任务和具有固定周期的重复任务。
也是存在一个问题,线程太多占用内存资源,会导致OOM,所以也是不建议使用
SingleThreadPool

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

单线程线程池,核心线程数和最大线程数量都是1,所以就是个单线程,但是任务可以有多个,所有的任务都是在同一个线程中按顺序执行。不需要考虑线程同步的问题。也没有超时机制。

问:为什么不推荐使用几种固定线程池?
是因为固定线程池中存在最大线程数设置为无限大,这种存在的问题就是会导致内存消耗很大,导致OOM。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值