美文网首页
线程池简单介绍

线程池简单介绍

作者: dawen92 | 来源:发表于2017-02-28 09:45 被阅读0次

ThreadPoolExecutor

线程池的真正实现,它的构造方法提供了一系列参数来配置线程池。
public ThreadPoolExecutor(int corePoolSize,
                              int maximumPoolSize,
                              long keepAliveTime,
                              TimeUnit unit,
                              BlockingQueue<Runnable> workQueue,
                              ThreadFactory threadFactory,
                              RejectedExecutionHandler handler) 

corePoolSize:线程池的核心线程数
maximumPoolSize:线程池所能容纳的最大线程数
keepAliveTime:非核心线程闲置时的超时时长,超过这个时长,非核心线程就会被回收
unit:指定keepAliveTime参数的时间单位
workQueue:线程池的任务队列,通过线程池的execute方法提交的Runnable对象会存储在这个参数中
threadFactory:线程工厂,为线程池提供创建新线程的功能
handler:任务队列已满或无法成功执行任务时的处理方式

Android中常用的线程池

FixedThreadPool,CachedThreadPool,ScheduledThreadPool,SingleThreadExecutor

1.FixedThreadPool:线程数量固定的线程池(只有核心线程且核心线程不会被回收)

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

2.CachedThreadPool:线程数量不定的线程池,只有非核心线程,且最大线程数为
Integer.MAX_VALUE(主要用于执行大量的耗时较少的任务)。

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

3.ScheduledThreadPool:核心线程数固定,非核心线程无限制,且非核心线程闲置时会被立即回收(主要用于执行定时任务和具有固定周期的重复任务)。

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

4.SingleThreadExecutor:只有一个核心线程,确保所有的任务都在同一个线程中按顺序执行

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

相关文章

网友评论

      本文标题:线程池简单介绍

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