线程池源码解析

201 阅读1分钟

线程池框架简介

image.png

  • Executor接口:提供execute方法提交任务
  • ExecutorService接口:提供可以跟踪任务执行结果的 submit方法 & 提供线程池关闭的方法(shutdown, shutdowNow)
  • ScheduledExecutorService接口:提供定时的schedule方法
  • AbstractExecutorService抽象类:实现submit方法
  • ThreadPoolExecutor: 线程池实现类
  • ScheduleThreadPoolExecutor:可以执行定时任务的线程池

线程池参数

public ThreadPoolExecutor(int corePoolSize,
                              int maximumPoolSize,
                              long keepAliveTime,
                              TimeUnit unit,
                              BlockingQueue<Runnable> workQueue,
                              ThreadFactory threadFactory,
                              RejectedExecutionHandler handler)
  • corePoolSize 核心线程数
  • maximumPoolSize 线程池最大大小
  • keepAliveTime 非核心线程空间存活时间
  • unit 存活时间单位
  • workQueue 工作队列
  • threadFactory 线程工厂
  • handler 拒绝策略

线程执行

threadPoolExecutor.execute(worker)

image.png