java线程池源码解析
程序员文章站
2022-05-04 08:54:04
1.从提交Runnable开始2. 具体流程(简化代码)public void execute(Runnable command) {addWorker(command);} private boolean addWorker(Runnable firstTask, boolean core) { w = new Worker(firstTask); //Worker中的Thread对象,真正执行工作的线程 final Thread t = w.thread;...
1.从提交Runnable开始
2. 具体流程(简化代码)
public void execute(Runnable command) {
addWorker(command);
}
private boolean addWorker(Runnable firstTask, boolean core) {
w = new Worker(firstTask);
//Worker中的Thread对象,真正执行工作的线程
final Thread t = w.thread;
//重要代码,会执行Worker中的run方法,进而执行runWorker()方法
t.start();
}
private final class Worker implements Runnable{
final Thread thread;
//firstTask肯定是先被执行的,随后新建的这个线程就会从任务队列中不断getTask(),没有Task则阻塞
Runnable firstTask;
Worker(Runnable firstTask) {
setState(-1); // inhibit interrupts until runWorker
this.firstTask = firstTask;
//注意此处,newThread时将自己传入了
//和上面联系起来
this.thread = getThreadFactory().newThread(this);
}
public void run() {
runWorker(this);
}
}
final void runWorker(Worker w) {
Thread wt = Thread.currentThread();
Runnable task = w.firstTask;
w.firstTask = null;
w.unlock(); // allow interrupts
boolean completedAbruptly = true;
try {
while (task != null || (task = getTask()) != null){
task.run();
}
private Runnable getTask() {
boolean timedOut = false; // Did the last poll() time out?
for (;;) {
try {
Runnable r = timed ?
workQueue.poll(keepAliveTime, TimeUnit.NANOSECONDS) :
workQueue.take();
if (r != null)
return r;
timedOut = true;
} catch (InterruptedException retry) {
timedOut = false;
}
}
}
总结:
1.为啥工作线程在firstTask结束后没有die? 因为内部有getTask(),是死循环,从阻塞队列中当取task时,取不到则阻塞
2.Woker对象,是一个封装线程的Runnable,addWoker内部,会执行Worker中的thread.start,进而执行runWoker,从而不断的获取task,执行task
本文地址:https://blog.csdn.net/weixin_38282516/article/details/107350764