JUC系列之线程池执行器
文章目录
工厂类Executors
- JUC系列之线程池执行器
- 工厂类Executors
- ThreadPoolExecutor
- 核心构造函数
- 默认线程工程方法
- CachedThreadPool
- FixedThreadPool
- SingleThreadExecutor
- 相关源码
- 成员变量
- 内部状态
- 内部类Worker
- 核心方法
- 任务的执行
- 线程退出
- 任务的关闭
- ScheduledThreadPoolExecutor
- ScheduledThreadPool
- 延迟性执行任务
- 周期性执行任务
- 相关源码
- 内部类ScheduledFutureTask
- 成员变量
- 构造函数
- 核心方法
- schedule(Runnable command, long delay, TimeUnit unit)
- scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit)
- scheduleWithFixedDelay(Runnable command, long initialDelay, long delay, TimeUnit unit)
- onShutdown()
- SingleScheduleThreadPool
可以由工程类Executors创建不同的线程池执行器。
ThreadPoolExecutor 核心构造函数当核心线程数量小于0时,或最大线程数量不大于0,或最大线程数小于核心线程数量,或当线程数超过corePoolSize时,线程空闲存活时长小于0时,将抛出IllegalArgumentException
。
当没有任务队列,或没有线程工厂,或没有拒绝策略时,将抛出NullPointerException
。
public ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue workQueue, ThreadFactory threadFactory, RejectedExecutionHandler handler) { if (corePoolSize scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit)
周期性执行任务,第一次执行延期时间之后,不等待第一次执行完成就会开始周期计时public ScheduledFuture scheduleWithFixedDelay(Runnable command, long initialDelay, long delay, TimeUnit unit)
周期性执行任务,在第一次执行完成之后,延迟固定时长后后开始下一次执行void shutdown()
尝试关闭线程池List shutdownNow()
立即关闭线程池 schedule(Runnable command, long delay, TimeUnit unit)通过
ScheduledFutureTask
的构造函数将Runnable/Callable
构造为本线程池可以执行的任务类型。同时调用decorateTask
方法执行用户自定义的逻辑,decorateTask
是一个用户可自定义扩展的方法,默认实现下直接返回封装的RunnableScheduledFuture
任务。public ScheduledFuture schedule(Runnable command, long delay, TimeUnit unit) { if (command == null || unit == null) throw new NullPointerException(); // 将Runnable转换成RunnableScheduledFuture RunnableScheduledFuture t = decorateTask(command, new ScheduledFutureTask(command, null, triggerTime(delay, unit))); // 执行任务主方法 delayedExecute(t); return t; }
protected RunnableScheduledFuture decorateTask( Runnable runnable, RunnableScheduledFuture task) { return task; }
private void delayedExecute(RunnableScheduledFuture task) { if (isShutdown()) // 线程池已经关闭,采用拒绝策略 reject(task); else { // 将RunnableScheduledFuture对象加入延迟队列 super.getQueue().add(task); // 判断线程是否关闭,或者任务已经无法运行,任务已经关闭 if (isShutdown() && !canRunInCurrentRunState(task.isPeriodic()) && remove(task)) task.cancel(false); else // 启动任务 ensurePrestart(); } }
void ensurePrestart() { // 计算工作线程的数量 int wc = workerCountOf(ctl.get()); // 若此时的工作线程的数据小于核心线程数则,新建一个核心线程,否则新建非核心线程。 if (wc
关注打赏
最近更新
- 深拷贝和浅拷贝的区别(重点)
- 【Vue】走进Vue框架世界
- 【云服务器】项目部署—搭建网站—vue电商后台管理系统
- 【React介绍】 一文带你深入React
- 【React】React组件实例的三大属性之state,props,refs(你学废了吗)
- 【脚手架VueCLI】从零开始,创建一个VUE项目
- 【React】深入理解React组件生命周期----图文详解(含代码)
- 【React】DOM的Diffing算法是什么?以及DOM中key的作用----经典面试题
- 【React】1_使用React脚手架创建项目步骤--------详解(含项目结构说明)
- 【React】2_如何使用react脚手架写一个简单的页面?