java基础----threadpoolexecutor
2022/7/22 2:00:12
本文主要是介绍java基础----threadpoolexecutor,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
线程池创建以及执行任务过程分析:
1. 创建线程池
Creates a new ThreadPoolExecutor with the given initial parameters.
Params:
corePoolSize – the number of threads to keep in the pool, even if they are idle, unless allowCoreThreadTimeOut is set
maximumPoolSize – the maximum number of threads to allow in the pool
keepAliveTime – when the number of threads is greater than the core, this is the maximum time that excess idle threads will wait for new tasks before terminating.
unit – the time unit for the keepAliveTime argument
workQueue – the queue to use for holding tasks before they are executed. This queue will hold only the Runnable tasks submitted by the execute method.
threadFactory – the factory to use when the executor creates a new thread
handler – the handler to use when execution is blocked because the thread bounds and queue capacities are reached
Throws:
IllegalArgumentException – if one of the following holds: corePoolSize < 0 keepAliveTime < 0 maximumPoolSize <= 0 maximumPoolSize < corePoolSize
NullPointerException – if workQueue or threadFactory or handler is null
1. public ThreadPoolExecutor(int corePoolSize, //线程池核心线程数,不管线程是否空闲 int maximumPoolSize, //线程池最大线程数目,当workqueue满了以后,在线程池中还可以创建线程的最大数目 long keepAliveTime,//超过核心线程数的线程在线程池中能呆的最久时间 TimeUnit unit,//上述时间的单位 BlockingQueue<Runnable> workQueue,//核心线程数满了以后,新来的任务需要被放到任务队列中 ThreadFactory threadFactory, RejectedExecutionHandler handler) 2. 参考https://www.cnblogs.com/moonfair/p/13477974.html
private final AtomicInteger ctl = new AtomicInteger(ctlOf(RUNNING, 0));//初始状态是Running 状态,0个工作线程,用来记录线程池状态和工作线程数量
private static final int COUNT_BITS = Integer.SIZE - 3; //将原子类的AtomicInteger的二进制位数(32位),拆分高3位(表示线程的运行状态)和低29位(表示工作线程数量)
private static final int CAPACITY = (1 << COUNT_BITS) - 1; // runState is stored in the high-order bits private static final int RUNNING = -1 << COUNT_BITS; private static final int SHUTDOWN = 0 << COUNT_BITS; private static final int STOP = 1 << COUNT_BITS; private static final int TIDYING = 2 << COUNT_BITS; private static final int TERMINATED = 3 << COUNT_BITS; // Packing and unpacking ctl private static int runStateOf(int c) { return c & ~CAPACITY; } private static int workerCountOf(int c) { return c & CAPACITY; } private static int ctlOf(int rs, int wc) { return rs | wc; }
2.执行任务过程分析:
-
当有任务进来时候,先通过ctl判断当前工作线程数目是否小于核心线程数
-
如果当前线程数<corePoolSize, 排除异常情况,通过compareAndIncrementWorkerCount增加工作线程数量
-
创建worker添加到 workers,添加过程需要添加ReentrantLock的lock锁,保证加入workers的hashset期间的线程安全。添加成功以后运行worker(本质是thread)的thread
-
如果当前线程数>=corePoolSize, 在当前线程池是运行状态的前提下,将任务添加到workQueue
-
如果workQueue的队列已经满了, 在当前工作线程小于最大线程数maximumPoolSize的前提下,和上面方式一样添加worker到workers的hashset。
-
如果当前工作线程大于最大线程数maximumPoolSize,则通过RejectedExecutionHandler的处理策略来处理。
3. 当有空闲线程时候如何从workQueue里取任务?
工作线程worker的run方法中,会一直循环运行,当当前的任务运行完以后,会从workQueue当中取任务来执行。
4. 最大线程超过核心线程的线程在线程池中的存在时间如何计算?
private Runnable getTask() { boolean timedOut = false; // Did the last poll() time out? for (;;) { int c = ctl.get(); int rs = runStateOf(c); // Check if queue empty only if necessary. if (rs >= SHUTDOWN && (rs >= STOP || workQueue.isEmpty())) { decrementWorkerCount(); return null; } int wc = workerCountOf(c); // Are workers subject to culling? boolean timed = allowCoreThreadTimeOut || wc > corePoolSize; if ((wc > maximumPoolSize || (timed && timedOut)) && (wc > 1 || workQueue.isEmpty())) { if (compareAndDecrementWorkerCount(c)) return null; continue; } try { Runnable r = timed ?workQueue.poll(keepAliveTime, TimeUnit.NANOSECONDS) ://如果timed为true说明worker有可能要被关闭,这里调用的代码含义:如果超过keepAliveTime纳秒还没取到任务,就返回null,后面会调用processWorkerExit把worker关闭 workQueue.take();//否则任务队列为空就阻塞在这里,直到任务队列再有任务
if (r != null) return r; timedOut = true; } catch (InterruptedException retry) { timedOut = false; } } }
5. 核心线程一直存在吗?
通过参数allowCoreThreadTimeOut来设置,默认为false,表示即便核心工作线程已经空闲,也还存活。如果设置为true,通过keepAliveTime来计算超时。
这篇关于java基础----threadpoolexecutor的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-11-23Springboot应用的多环境打包入门
- 2024-11-23Springboot应用的生产发布入门教程
- 2024-11-23Python编程入门指南
- 2024-11-23Java创业入门:从零开始的编程之旅
- 2024-11-23Java创业入门:新手必读的Java编程与创业指南
- 2024-11-23Java对接阿里云智能语音服务入门详解
- 2024-11-23Java对接阿里云智能语音服务入门教程
- 2024-11-23JAVA对接阿里云智能语音服务入门教程
- 2024-11-23Java副业入门:初学者的简单教程
- 2024-11-23JAVA副业入门:初学者的实战指南