marco和孙丹菲,ppt答辩技巧,风云皇后
线程池原理和使用在面试中被高频问到,比如阿里的面试题。下面我们针对问题来进行回答。
线程池的使用场景有2:
1, 高并发场景:比如tomcat的处理机制,内置了线程池处理http请求;
2,异步任务处理:比如spring的异步方法改造,增加@asyn注解对应了一个线程池;
使用线程池带来的好处有4:
1, 降低系统的消耗:线程池复用了内部的线程对比处理任务的时候创建线程处理完毕销毁线程降低了线程资源消耗
2,提高系统的响应速度:任务不必等待新线程创建,直接复用线程池的线程执行
3,提高系统的稳定性:线程是重要的系统资源,无限制创建系统会奔溃,线程池复用了线程,系统会更稳定
4,提供了线程的可管理功能:暴露了方法,可以对线程进行调配,优化和监控
当向线程池中提交一个任务,线程池内部是如何处理任务的?
先来个流程图,标识一下核心处理步骤:
1,线程池内部会获取activecount, 判断活跃线程的数量是否大于等于corepoolsize(核心线程数量),如果没有,会使用全局锁锁定线程池,创建工作线程,处理任务,然后释放全局锁;
2,判断线程池内部的阻塞队列是否已经满了,如果没有,直接把任务放入阻塞队列;
3,判断线程池的活跃线程数量是否大于等于maxpoolsize,如果没有,会使用全局锁锁定线程池,创建工作线程,处理任务,然后释放全局锁;
4,如果以上条件都满足,采用饱和处理策略处理任务。
说明:使用全局锁是一个严重的可升缩瓶颈,在线程池预热之后(即内部线程数量大于等于corepoolsize),任务的处理是直接放入阻塞队列,这一步是不需要获得全局锁的,效率比较高。
源码如下:
public void execute(runnable command) { if (command == null) throw new nullpointerexception(); int c = ctl.get(); if (workercountof(c) < corepoolsize) { if (addworker(command, true)) return; c = ctl.get(); } if (isrunning(c) && workqueue.offer(command)) { int recheck = ctl.get(); if (! isrunning(recheck) && remove(command)) reject(command); else if (workercountof(recheck) == 0) addworker(null, false); } else if (!addworker(command, false)) reject(command); }
注释没保留,注释的内容就是上面画的流程图;
代码的逻辑就是流程图中的逻辑。
执行任务模型如下:
线程池中的线程执行任务分为以下两种情况:
1, 创建一个线程,会在这个线程中执行当前任务;
2,工作线程完成当前任务之后,会死循环从blockingqueue中获取任务来执行;
代码如下:
private boolean addworker(runnable firsttask, boolean core) { retry: for (int c = ctl.get();;) { // check if queue empty only if necessary. if (runstateatleast(c, shutdown) && (runstateatleast(c, stop) || firsttask != null || workqueue.isempty())) return false; for (;;) { if (workercountof(c) >= ((core ? corepoolsize : maximumpoolsize) & count_mask)) return false; if (compareandincrementworkercount(c)) break retry; c = ctl.get(); // re-read ctl if (runstateatleast(c, shutdown)) continue retry; // else cas failed due to workercount change; retry inner loop } } boolean workerstarted = false; boolean workeradded = false; worker w = null; try { w = new worker(firsttask); final thread t = w.thread; if (t != null) { final reentrantlock mainlock = this.mainlock; mainlock.lock(); try { // recheck while holding lock. // back out on threadfactory failure or if // shut down before lock acquired. int c = ctl.get(); if (isrunning(c) || (runstatelessthan(c, stop) && firsttask == null)) { if (t.isalive()) // precheck that t is startable throw new illegalthreadstateexception(); workers.add(w); int s = workers.size(); if (s > largestpoolsize) largestpoolsize = s; workeradded = true; } } finally { //释放锁 mainlock.unlock(); } if (workeradded) { //执行提交的任务,然后设置工作线程为启动状态 t.start(); workerstarted = true; } } } finally { if (! workerstarted) addworkerfailed(w); } return workerstarted; }
从代码中可以看到:把工作线程增加到线程池,然后释放锁,执行完提交进来的任务之后,新建的工作线程状态为启动状态;
创建线程池使用线程池的构造函数来创建。
/** * creates a new {@code threadpoolexecutor} with the given initial * parameters. * * @param corepoolsize the number of threads to keep in the pool, even * if they are idle, unless {@code allowcorethreadtimeout} is set * @param maximumpoolsize the maximum number of threads to allow in the * pool * @param 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. * @param unit the time unit for the {@code keepalivetime} argument * @param workqueue the queue to use for holding tasks before they are * executed. this queue will hold only the {@code runnable} * tasks submitted by the {@code execute} method. * @param threadfactory the factory to use when the executor * creates a new thread * @param 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:<br> * {@code corepoolsize < 0}<br> * {@code keepalivetime < 0}<br> * {@code maximumpoolsize <= 0}<br> * {@code maximumpoolsize < corepoolsize} * @throws nullpointerexception if {@code workqueue} * or {@code threadfactory} or {@code handler} is null */ public threadpoolexecutor(int corepoolsize, int maximumpoolsize, long keepalivetime, timeunit unit, blockingqueue<runnable> workqueue, threadfactory threadfactory, rejectedexecutionhandler handler)
参数简单翻译过来,然后做一下备注:
rejectedexecutionhandler分为4种:
abort:直接抛出异常
discard:静默丢弃最后的任务
discardoldest:静默丢弃最先入队的任务,并处理当前任务
callerruns:调用者线程来执行任务
也可以自定义饱和策略。实现rejectedexecutionhandler即可。
线程池中提交任务的方法有2:
1,void execute(runable) ,没有返回值,无法判断任务的执行状态。
2,future
如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复
浅析我对 String、StringBuilder、StringBuffer 的理解
使用IDEA搭建SSM框架的详细教程(spring + springMVC +MyBatis)
Springboot整合freemarker 404问题解决方案
引入mybatis-plus报 Invalid bound statement错误问题的解决方法
网友评论