Java:ThreadPoolExecutor线程池知识体系

线程和线程池模型图

在这里插入图片描述
在这里插入图片描述

继承体系

在这里插入图片描述

执行流程

在这里插入图片描述

构造方法

ThreadPoolExecutor的构造方法

public class ThreadPoolExecutor extends AbstractExecutorService {
    
    
    public ThreadPoolExecutor(
        int corePoolSize,
        int maximumPoolSize,
        long keepAliveTime,
        TimeUnit unit,
        BlockingQueue<Runnable> workQueue
    )

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

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

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

各个参数的解读如下:

  • corePoolSize:核心线程数量,用于执行任务的核心线程数。
  • maximumPoolSize:最大线程数量,线程池中允许创建线程的最大数量
  • keepAliveTime:空闲线程存活的时间。只有当线程池中的线程数大于 corePoolSize 时,这个参数才会起作用
  • unit:空闲线程存活的时间单位
  • workQueue:任务队列,用于存储还没来得及执行的任务
  • threadFactory:线程工厂。用于执行任务时创建新线程的工厂
  • handler:拒绝策略,当线程池和和队列容量处于饱满,使用某种策略来拒绝任务提交

线程池应用

newSingleThreadExecutor

单线程的线程池

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

newFixedThreadPool

固定大小线程数的线程池

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

newCachedThreadPool

可缓存的无界线程池

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

newScheduledThreadPool

周期性的线程池

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

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

参考文章
3分钟带你秒懂线程池设计机制

猜你喜欢

转载自blog.csdn.net/mouday/article/details/140430800