线程池ThreadPoolExecutor

构造方法

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

参数意义:

coreProolSize:线程池核心线程数

maximumPoolSize:线程池所能容纳的最大线程数

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

unit:用于指定keepAliveTime参数的时间单位,常用的有毫秒、秒、分钟

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

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

遵循规则:

1)如果线程池中的线程数量未达到核心线程的数量,那么会直接启动一个核心线程来执行任务

2)如果线程池中的线程数量已经达到或者超过核心线程的数量,那么任务会被插入到任务队列中排队等待执行

3)如果在步骤2中无法将任务插入到任务队列中,这往往是由于任务队列已满,这个时候如果线程数量未达到线程池规定的最大值,那么会立刻启动一个非核心线程来执行任务

4)如果步骤3中线程数量已经达到线程池规定的最大值,那么就拒绝执行此任务,ThreadPoolExecutor会调用RejectedExecutionHandlerrejectedExecution方法来通知调用者(当任务队列已满或无法成功执行任务时调用)

AsyncTask的配置如下

1)核心线程数=CPU核心数+1

2)线程池最大线程数=CPU核心数的2倍+1

3)核心线程无超时机制,非核心线程在闲置时的超时时间为1秒

4)任务队列的容量为128

线程池分类:

1)FixedThreadPool

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

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

2)CachedThreadPool

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

只有非核心线程,最大线程数为任意大,超时机制为60秒,任务队列相当于一个空集合。此类线程适合执行大量的耗时较少的任务

3)ScheduleThreadPool

public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize){
    return new ScheduledThreadPoolExecutor(corePoolSize);
}

public ScheduledThreadPoolExecutor(int corePoolSize){
    super(corePoolSize,Integer.MAX_VALUE,0,NANOSECONDS,new DelayedWorkQueue())
}

核心线程数量固定,非核心线程数量没有限制,且超时机制为0,即立刻回收。此类线程主要用于执行定时任务和具有固定周期的重复任务。

4)SingleThreadExecutor

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

内部只有一个核心线程,确保所有任务在同一个线程中按顺序执行。意义在于统一所有的外界任务到一个线程中,使得不需要处理线程同步的问题。

原文地址:https://www.cnblogs.com/anni-qianqian/p/8329723.html