ThreadPoolExecutor源码阅读
来源:互联网 发布:侠客行 叮叮当当 知乎 编辑:程序博客网 时间:2024/06/08 03:19
1.线程池解决的问题
线程池解决两个问题
一是复用线程,减少创建销毁线程带来系统开销;
二是限定系统资源使用边界,避免大量线程消耗尽系统内存
适用于互不依赖,运行时间短,不需要对线程控制操作的线程
2.ThreadPoolExecutor主流程
添加任务时,
1.若线程数量小于corePoolSize,则新增线程执行任务
2.若线程数量大于等于corePoolSize且queue队列非满,任务添加到queue
3.若线程数量大于等于corePoolSize且queue队列满,则新增线程执行任务直到线程数量到达maximumPoolSize
4.若线程池满,任务无法被执行,执行用户定义或者默认的RejectedExecutionHandler
执行任务
执行线程持续从queue队列中获取任务并执行
3.主要方法
execute
public void execute(Runnable command) { if (command == null) throw new NullPointerException(); int c = ctl.get(); if (workerCountOf(c) < corePoolSize) {//线程少于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);//若队列满或者线程池关闭,执行rejecthandler }
private boolean addWorker(Runnable firstTask, boolean core) { retry: for (;;) { int c = ctl.get(); int rs = runStateOf(c); // Check if queue empty only if necessary. if (rs >= SHUTDOWN &&//线程池非运行状态 ! (rs == SHUTDOWN &&//线程池关闭时任务队列非空,可以添加线程,shutdown状态不接受新任务,所以firstTask为null firstTask == null && ! workQueue.isEmpty())) return false; 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 } } boolean workerStarted = false; boolean workerAdded = false; Worker w = null; try { final ReentrantLock mainLock = this.mainLock; w = new Worker(firstTask); final Thread t = w.thread; if (t != null) { mainLock.lock(); try { // Recheck while holding lock. // Back out on ThreadFactory failure or if // shut down before lock acquired. int c = ctl.get(); int rs = runStateOf(c); if (rs < SHUTDOWN || (rs == SHUTDOWN && 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();//开始执行线程,调用的runWorker方法 workerStarted = true; } } } finally { if (! workerStarted) addWorkerFailed(w); } return workerStarted; }
final void runWorker(Worker w) { Thread wt = Thread.currentThread(); Runnable task = w.firstTask; w.firstTask = null; w.unlock(); // allow interrupts boolean completedAbruptly = true; try { //执行第一个任务或者从queue队列获取新任务,循环执行 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); } }
阅读全文
0 0
- ThreadPoolExecutor源码阅读
- ThreadPoolExecutor源码阅读
- Java源码阅读之ThreadPoolExecutor
- java源码阅读之ThreadPoolExecutor
- java并发-ThreadPoolExecutor源码阅读笔记
- 阅读Java线程池ThreadPoolExecutor源码(上)
- ThreadPoolExecutor源码
- ThreadPoolExecutor源码
- 理解ThreadPoolExecutor源码(二)execute函数的巧妙设计和阅读心得
- ThreadPoolExecutor 源码分析
- ThreadPoolExecutor源码分析
- ThreadPoolExecutor源码分析
- ThreadPoolExecutor源码解析
- ThreadPoolExecutor源码解析
- ThreadPoolExecutor源码解析
- [Java]ThreadPoolExecutor源码分析
- ThreadPoolExecutor源码分析
- JUC - ThreadPoolExecutor 源码分析
- MySQL存储引擎--MyISAM与InnoDB区别
- c++11——move/forward
- Gradle task简单使用
- 状态模式【State Pattern】
- 2017年上半年软件设计师考试真题及答案(上午+下午)免费
- ThreadPoolExecutor源码阅读
- Lock和synchronized比较详解
- 接口测试整理
- 正则表达式 Exel单元格
- sql 设置主键
- ip地址 子网掩码 默认网关的联系
- C++11:深入理解右值引用,move语义和完美转发
- 微信小程序Redux绑定
- Myeclipse安装Gradle插件