二、ThreadPoolExecutor
来源:互联网 发布:泰克网络实验室怎么样 编辑:程序博客网 时间:2024/06/09 16:08
二、ThreadPoolExecutor
核心参数作用请参考(一、线程池概要)
new ThreadPoolExecutor(xx,xx,xx…).submit(runnable)
1、类依赖关系
ThreadPoolExecutor
extends AbstractExecutorService
implements ExecutorService
- extends Executor
2、运行流程
a) 如果运行线程数 < corePoolSize
- 创建线程,运行当前任务
b) 如果运行线程数 >= corePoolSize,并且任务队列里任务数量没有满
将任务放到任务队列(workQueue)
已创建的线程会轮询任务队列,如果任务队列里有值,则会从任务队列中取任务来执行
c) 如果队列已满,并且运行线程数 < maximumPoolSize
- 创建线程,运行当前任务
d) 否则执行 拒绝策略
handler.rejectedExecution(command, this);
ThreadPoolExecutorpublic void execute(Runnable command) { if (command == null) throw new NullPointerException(); int c = ctl.get(); //a 创建worker,并加入workers if (workerCountOf(c) < corePoolSize) { if (addWorker(command, true)) return; c = ctl.get(); } //b 加入任务队列,如果队列满了,workQueue.offer返回失败 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); } //c/d 新建worker,超过最大容量则新建失败 else if (!addWorker(command, false)) reject(command);}
3、核心方法解析
3.1 addWorker(Runnable firstTask, boolean core)
描述
- 创建worker,一个worker里一个线程
参数
firstTask:表示当前任务
core:true表示使用corePoolSize,false表示使用maximumPoolSize
ThreadPoolExecutorprivate boolean addWorker(Runnable firstTask, boolean core) { retry: for (;;) { int c = ctl.get(); int rs = runStateOf(c); // 判断线程池状态,如果非running状态,返回失败,不创建worker if (rs >= SHUTDOWN && ! (rs == SHUTDOWN && firstTask == null && ! workQueue.isEmpty())) return false; //先拿到当前运行的线程数,core为true则比较corePoolSize,否则比较maximumPoolSize //如果超过线程池容量,则返回失败,不创建worker //增加运行线程数 for (;;) { int wc = workerCountOf(c); if (wc >= CAPACITY || wc >= (core ? corePoolSize : maximumPoolSize)) return false; if (compareAndIncrementWorkerCount(c)) break retry; c = ctl.get(); // Re-read ctl if (runStateOf(c) != rs) continue retry; // else CAS failed due to workerCount change; retry inner loop } } //创建worker,里面会新建线程 //然后启动线程 //worker里覆盖了run方法,会不断从任务队列里拿任务来执行 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 rs = runStateOf(ctl.get()); if (rs < SHUTDOWN || (rs == SHUTDOWN && firstTask == null)) { if (t.isAlive()) // precheck that t is startable throw new IllegalThreadStateException(); //加入到workers 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;}
3.2 worker.run()
描述
运行worker
public void run() { runWorker(this);}//启动workerfinal void runWorker(Worker w) { Thread wt = Thread.currentThread(); Runnable task = w.firstTask; w.firstTask = null; w.unlock(); // allow interrupts boolean completedAbruptly = true; try { //先取当前任务,执行完之后,从任务队列里取任务 //如果getTask()返回null,则意味着线程结束 while (task != null || (task = getTask()) != null) { w.lock(); // If pool is stopping, ensure thread is interrupted; // if not, ensure thread is not interrupted. This // requires a recheck in second case to deal with // shutdownNow race while clearing interrupt //如果线程池停止,并且当前线程没有打上中断标识,则需要打上中断 if ((runStateAtLeast(ctl.get(), STOP) || (Thread.interrupted() && runStateAtLeast(ctl.get(), STOP))) && !wt.isInterrupted()) wt.interrupt(); try { beforeExecute(wt, task); Throwable thrown = null; try { task.run(); } catch (RuntimeException x) { thrown = x; throw x; } catch (Error x) { thrown = x; throw x; } catch (Throwable x) { thrown = x; throw new Error(x); } finally { afterExecute(task, thrown); } } finally { task = null; w.completedTasks++; w.unlock(); } } completedAbruptly = false; } finally { processWorkerExit(w, completedAbruptly); }}
3.3 worker.getTask()
描述
从任务队列中获取任务,涉及线程池参数:corePoolSize、keepAliveTime
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. //如果线程池关闭,并且线程池为空,清除worker数量 if (rs >= SHUTDOWN && (rs >= STOP || workQueue.isEmpty())) { decrementWorkerCount(); return null; } int wc = workerCountOf(c); // 需要判断worker空闲时间,这里可以看到,allowCoreThreadTimeOut默认为false,只有超过corePoolSize的线程会受空闲时间keepAliveTime的影响 boolean timed = allowCoreThreadTimeOut || wc > corePoolSize; //如果worker数量超过maximumPoolSize,或者已经空闲了超过keepAliveTime,返回null,即线程会结束 if ((wc > maximumPoolSize || (timed && timedOut)) && (wc > 1 || workQueue.isEmpty())) { if (compareAndDecrementWorkerCount(c)) return null; continue; } //如果需要判断worker空闲时间 //timed==true:从队列中取任务,如果队列为空并且阻塞了超过keepAliveTime,说明队列没有值,返回null,该多余线程相当于空闲了keepAliveTime,即将会退出 //timed==false:从队列中取任务,如果队列为空,则一直阻塞,直到队列中有值 try { Runnable r = timed ? workQueue.poll(keepAliveTime, TimeUnit.NANOSECONDS) : workQueue.take(); if (r != null) return r; timedOut = true; } catch (InterruptedException retry) { timedOut = false; } }}
阅读全文
0 0
- 二、ThreadPoolExecutor
- Java的ThreadPoolExecutor(二)
- ThreadPoolExecutor(二)——execute
- 深入分析ThreadPoolExecutor之二
- ThreadPoolExecutor
- ThreadPoolExecutor
- ThreadPoolExecutor
- ThreadPoolExecutor
- ThreadPoolExecutor
- ThreadPoolExecutor
- ThreadPoolExecutor
- ThreadPoolExecutor
- ThreadPoolExecutor
- ThreadPoolExecutor
- ThreadPoolExecutor
- ThreadPoolExecutor
- ThreadPoolExecutor
- ThreadPoolExecutor
- ffmpeg 列表
- 局域网群聊工具
- 决策树, 森林
- JAVA自定义注解实现SQL语句自动生成DEMO(2)
- POJ 2485 Highways
- 二、ThreadPoolExecutor
- 找球号(一)
- v-for循环渲染列表时,怎么直接把从对象取出的值赋值给class属性
- 阿里云+wordpress搭建个人博客
- hdu3944 lucas定理+阶乘预处理
- 大数据的存取
- Machine Learning In Action-Chapter8 线性回归
- HDU 4507 数位DP
- Effective Modern C++ Item 2