JDK线程池的原理

文章目录

1.线程池的概念

1.我们这里说的线程池主要是JDK中提供的线程池;
2.线程池,主要是基于频繁的创建和销毁线程比较耗费资源,所以我们在项目启动的过程中,提前创建包含一定数量线程的
  线程池(池子)3.后面请求过来的时候,直接从线程池中获取可用的线程即可;  

2.线程池的优点

2.1.减少资源的消耗

1.这里减少资源的消耗,主要是由于提供了线程池,一定数量上,可以减少因为线程的创建和销毁而带来的CPU内存资源消耗;

2.2.提高请求访问速度(响应速度)

1.因为我们有了线程池,减少了线程的创建和销毁时间,这样响应速度和访问速度都能够提高;

2.3.便于对线程的管理

1.因为有了线程池,线程的数量是稳定的,保证了系统的稳定性
2.同时,我们可以便于对线程池中的线程进行统一的管理,调优等操作;

3.JDK API

3.1.线程池对象ThreadPoolExecutor(ExecutorService子类)

1.这里我们着重看一下构造一个线程池ThreadPoolExecutor所需要的因子参数;
2.下面是对参数的介绍
int corePoolSize, 									#核心线程数量
int maximumPoolSize,								#最大线程数量
long keepAliveTime,									#线程存活时间
TimeUnit unit,											#线程存活时间单位,keepAliveTime的单位
BlockingQueue<Runnable> workQueue,  #存储请求任务的线程队列
ThreadFactory threadFactory,
RejectedExecutionHandler handler

在这里插入图片描述

3.2.创建线程池的核心工具类对象-Executors

1.首先 Executors是一个创建线程池的工具类;
2.Executors中提供了一些列静态的创建线程池对象ExecutorService;的一系列的方法,返回线程池ExecutorService;
3.这里我们先简单的介绍一下ThreadPoolExecutor对象(ExecutorService子类)  

3.3.Executors 创建线程池的核心方法

3.3.1.创建只有一个线程的线程池:newSingleThreadExecutor

public static ExecutorService newSingleThreadExecutor() {
        return new FinalizableDelegatedExecutorService
            (new ThreadPoolExecutor(1, 1,
                                    0L, TimeUnit.MILLISECONDS,
                                    new LinkedBlockingQueue<Runnable>()));
}

3.3.2.创建固定线程数量的线程池:newFixedThreadPool

    public static ExecutorService newFixedThreadPool(int nThreads, ThreadFactory threadFactory) {
        return new ThreadPoolExecutor(nThreads, nThreads,
                                      0L, TimeUnit.MILLISECONDS,
                                      new LinkedBlockingQueue<Runnable>(),
                                      threadFactory);
    }

3.3.3.创建没有限制数量的线程池:newCachedThreadPool

   public static ExecutorService newCachedThreadPool(ThreadFactory threadFactory) {
        return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
                                      60L, TimeUnit.SECONDS,
                                      new SynchronousQueue<Runnable>(),
                                      threadFactory);
    }
1.这里的线程数量所谓没有限制,是一个相对值,因为最大值为2^32-1,几乎是一个够用的一个数量
2.线程池会根据实际的需要去自动的调整线程池的大小;
3.60秒后线程自动被回收;

3.3.4.周期性任务的调度的线程池:ScheduledThreadPoolExecutor

    public static ScheduledExecutorService newScheduledThreadPool(
            int corePoolSize, ThreadFactory threadFactory) {
        return new ScheduledThreadPoolExecutor(corePoolSize, threadFactory);
    }

1.所谓周期性任务的调度,周期性的执行队列中的请求

4.多线程使用引入样例

package com.gaoxinfu.demo.jdk.rt.java.util.concurrent;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @Description:
 * @Author: gaoxinfu
 * @Date: 2020-05-20 14:07
 */
public class ExecutorsDemo {
    public static void main(String[] args) {

        ExecutorService threadPoolExecutor= Executors.newCachedThreadPool();

        for (int i = 0; i < 10; i++) {
            final int index = i;
            try {
                Thread.sleep(index * 1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            threadPoolExecutor.execute(new Runnable() {
                @Override
                public void run() {
                    System.out.println("index = "+index);
                }
            });
        }
    }
}

4.多线程执行流程

4.1.线程池使用入口:ThreadPoolExecutor.execute

1.从上面的样例,我们可以知道,线程池使用的入口为:
  ThreadPoolExecutor.execute(Runnable runnable)

4.2.线程池ThreadPoolExecutor构造方法参数

 /**
     * Creates a new {@code ThreadPoolExecutor} with the given initial
     * parameters and default thread factory.
     * 
     * @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 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 handler} is null
     */  
public ThreadPoolExecutor(int corePoolSize,
                              int maximumPoolSize,
                              long keepAliveTime,
                              TimeUnit unit,
                              BlockingQueue<Runnable> workQueue,
                              RejectedExecutionHandler handler) {
        this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
             Executors.defaultThreadFactory(), handler);
}

4.2.1.corePoolSize:核心线程池数量

1.corePoolSize:我们可以简单理解就是应用运行的过程中,需要保证的线程池中一个至少应该运行的线程的数量;
2.但是这里有一个特殊情况:就是我们

4.2.2.maximumPoolSize:最大线程池数量

4.2.3.keepAliveTime:线程空闲时间长度

4.2.4.unit:线程空闲时间长度单位

4.2.5.workQueue:线程池中阻塞待处理的队列

4.2.6.handler:线程池无法处理新的请求之后的拒绝策略

4.3.线程整体执行流程图

4.3.1.线程池内部结构解析

在这里插入图片描述

1.corePoolSize实际上我们可以认为是隶属于maxmumPoolSize的子集
2.WorkerQueue是一个队列,这个队列主要是基于在新的请求进来之后,线程池数量大于corePoolSize时,会进去这个
  WorkerQueue队列

4.3.2.线程池流程判断

在这里插入图片描述

1.请求过来之后,进去线程池之后,首先查看核心线程池当前是否有空余的线程,如果有,则创建线程进行执行;
2.如果核心线程池corePoolSize没有多余的线程,那么判断WorkerQueue队列是否已经满;
  如果已满,那么进行判断进行步骤3的处理;
  如果未满,进入WorkerQueue队列,等待线程池中空余线程Thread的处理;
3.判断maxmumPoolSize是否已满
     如果没有剩余线程,直接执行线程池指定的拒绝策略;
     如果还有剩余线程,直接创建线程执行的任务,处理当前的请求;

4.3.3.线程池的状态

    /**
     * The main pool control state, ctl, is an atomic integer packing
     * two conceptual fields
     *   workerCount, indicating the effective number of threads
     *   runState,    indicating whether running, shutting down etc
     *
     * In order to pack them into one int, we limit workerCount to
     * (2^29)-1 (about 500 million) threads rather than (2^31)-1 (2
     * billion) otherwise representable. If this is ever an issue in
     * the future, the variable can be changed to be an AtomicLong,
     * and the shift/mask constants below adjusted. But until the need
     * arises, this code is a bit faster and simpler using an int.
     *
     * The workerCount is the number of workers that have been
     * permitted to start and not permitted to stop.  The value may be
     * transiently different from the actual number of live threads,
     * for example when a ThreadFactory fails to create a thread when
     * asked, and when exiting threads are still performing
     * bookkeeping before terminating. The user-visible pool size is
     * reported as the current size of the workers set.
     *
     * The runState provides the main lifecycle control, taking on values:
     *
     *   RUNNING:  Accept new tasks and process queued tasks
     *   SHUTDOWN: Don't accept new tasks, but process queued tasks
     *   STOP:     Don't accept new tasks, don't process queued tasks,
     *             and interrupt in-progress tasks
     *   TIDYING:  All tasks have terminated, workerCount is zero,
     *             the thread transitioning to state TIDYING
     *             will run the terminated() hook method
     *   TERMINATED: terminated() has completed
     *
     * The numerical order among these values matters, to allow
     * ordered comparisons. The runState monotonically increases over
     * time, but need not hit each state. The transitions are:
     *
     * RUNNING -> SHUTDOWN
     *    On invocation of shutdown(), perhaps implicitly in finalize()
     * (RUNNING or SHUTDOWN) -> STOP
     *    On invocation of shutdownNow()
     * SHUTDOWN -> TIDYING
     *    When both queue and pool are empty
     * STOP -> TIDYING
     *    When pool is empty
     * TIDYING -> TERMINATED
     *    When the terminated() hook method has completed
     *
     * Threads waiting in awaitTermination() will return when the
     * state reaches TERMINATED.
     *
     * Detecting the transition from SHUTDOWN to TIDYING is less
     * straightforward than you'd like because the queue may become
     * empty after non-empty and vice versa during SHUTDOWN state, but
     * we can only terminate if, after seeing that it is empty, we see
     * that workerCount is 0 (which sometimes entails a recheck -- see
     * below).
     */
    // 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;

4.3.3.1.线程池的几种状态介绍

4.3.3.1.1.RUNNING:接收新任务,同时处理已经在队列中的任务
RUNNING:  Accept new tasks and process queued tasks
4.3.3.1.2.SHUTDOWN :不接受新任务,但是处理已经在队列中的任务
SHUTDOWN:Don't accept new tasks, but process queued tasks
4.3.3.1.3.STOP状态:不接受新任务,不处理队列中任务,中断正在进行的任务
Don't accept new tasks, don't process queued tasks,and interrupt in-progress tasks
4.3.3.1.4.TIDYING状态:所有的任务终止,WorkerCount为0,进入TIDYING状态,开始调用terminated()方法
TIDYING:All tasks have terminated, workerCount is zero,
                  the thread transitioning to state TIDYING
                  will run the terminated() hook method
4.3.3.1.5.TERMINATED :terminated() 调用结束的时候状态
TERMINATED:terminated() has completed

4.3.3.2.线程池状态的变化关系

     * RUNNING -> SHUTDOWN
     *    On invocation of shutdown(), perhaps implicitly in finalize()
     * (RUNNING or SHUTDOWN) -> STOP
     *    On invocation of shutdownNow()
     * SHUTDOWN -> TIDYING
     *    When both queue and pool are empty
     * STOP -> TIDYING
     *    When pool is empty
     * TIDYING -> TERMINATED
     *    When the terminated() hook method has completed

在这里插入图片描述

1.应用启动的时候,线程池就进入了RUNNING状态;
2.RUNNING状态下,一旦调用shutdown()方法,进入SHUTDOWN状态
3.TIDYING 翻译为整理,为调用terminated()之前的一个状态

4.3.3.3.线程池状态的二进制标示介绍

    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;

转换为二进制 CPU内存中的存储形式

    @Test
    public void ctl(){
        System.out.println(Integer.toBinaryString(-1));
        System.out.println("RUNNING    = " +Integer.toBinaryString((-1 << (Integer.SIZE - 3))));
        System.out.println("SHUTDOWN   = " +Integer.toBinaryString((0 << (Integer.SIZE - 3))));
        System.out.println("STOP       = " +Integer.toBinaryString((1 << (Integer.SIZE - 3))));
        System.out.println("TIDYING    = " +Integer.toBinaryString((2 << (Integer.SIZE - 3))));
        System.out.println("TERMINATED = " +Integer.toBinaryString((3 << (Integer.SIZE - 3))));
    }
11111111111111111111111111111111
RUNNING    = 11100000000000000000000000000000   #相当于 011100000 00000000 00000000 00000000
SHUTDOWN   = 0                                  #相当于 000000000 00000000 00000000 00000000
STOP       = 100000000000000000000000000000     #相当于 000100000 00000000 00000000 00000000
TIDYING    = 1000000000000000000000000000000    #相当于 001000000 00000000 00000000 00000000
TERMINATED = 1100000000000000000000000000000    #相当于 001100000 00000000 00000000 00000000

第一位是符号位,也就是这5个状态是通过高三位的保存了状态
关于位移有符号位移运算的介绍可以参考下面的地址
https://blog.csdn.net/u014636209/article/details/106405242

4.3.4.从源码看流程

		/**
     * Executes the given task sometime in the future.  The task
     * may execute in a new thread or in an existing pooled thread.
     *
     * If the task cannot be submitted for execution, either because this
     * executor has been shutdown or because its capacity has been reached,
     * the task is handled by the current {@code RejectedExecutionHandler}.
     *
     * @param command the task to execute
     * @throws RejectedExecutionException at discretion of
     *         {@code RejectedExecutionHandler}, if the task
     *         cannot be accepted for execution
     * @throws NullPointerException if {@code command} is null
     */
    public void execute(Runnable command) {
        if (command == null)
            throw new NullPointerException();
        /*
         * Proceed in 3 steps:
         *
         * 1. If fewer than corePoolSize threads are running, try to
         * start a new thread with the given command as its first
         * task.  The call to addWorker atomically checks runState and
         * workerCount, and so prevents false alarms that would add
         * threads when it shouldn't, by returning false.
         *
         * 2. If a task can be successfully queued, then we still need
         * to double-check whether we should have added a thread
         * (because existing ones died since last checking) or that
         * the pool shut down since entry into this method. So we
         * recheck state and if necessary roll back the enqueuing if
         * stopped, or start a new thread if there are none.
         *
         * 3. If we cannot queue task, then we try to add a new
         * thread.  If it fails, we know we are shut down or saturated
         * and so reject the task.
         */
      	//获取当前线程池的状态
        int c = ctl.get();
      
        //1.判断Worker(正在运行的线程)数量是否小于核心线程池的数量
        if (workerCountOf(c) < corePoolSize) {
            //核心线程池还有空闲的线程,将当前请求加入到Worker之中,启动新的线程
            //具体addWorker的方法 可以查看4.3.3.1
            if (addWorker(command, true))
                return;
            c = ctl.get();
        }
        
        //2.
        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);
    }

4.3.4.1.我们先来了解一个AtomicInteger ctl变量

    private final AtomicInteger ctl = new AtomicInteger(ctlOf(RUNNING, 0));

     // 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; 
    }
4.3.4.1.1.ctlOf的两个属性:线程池的运行状态和线程池的Worker数量
    private final AtomicInteger ctl = new AtomicInteger(ctlOf(RUNNING, 0));

    private static int ctlOf(int rs, int wc) { 
        return rs | wc; 
    }
1.首先,使用AtomicInteger类型的变量存储了线程池的两个属性:线程池的运行状态和线程池的Worker数量

我们前面看知道线程池的一个状态的二进制存储的问题,如下

RUNNING    = 11100000000000000000000000000000   #相当于 011100000 00000000 00000000 00000000
SHUTDOWN   = 0                                  #相当于 000000000 00000000 00000000 00000000
STOP       = 100000000000000000000000000000     #相当于 000100000 00000000 00000000 00000000
TIDYING    = 1000000000000000000000000000000    #相当于 001000000 00000000 00000000 00000000
TERMINATED = 1100000000000000000000000000000    #相当于 001100000 00000000 00000000 00000000

从上面,可以看到,第一位为符号位(0标示正) 然后第二位到第四位保存类线程池的状态
我们的Worker线程池的数量估计认为3*8+5=29,也就是29^2-1 个
那么可以看出,前面四个是线程池的状态,后面29个二进制可以认为是Worker数量
这样我们就可以对他俩的二进制进行运算,可以算的线程池的状态或者Worker的数量,具体见下面的分析

在这里插入图片描述

4.3.4.1.2.获取线程池的状态:runStateOf
 private static int runStateOf(int c)     { 
        return c & ~CAPACITY; 
 }
1.因为我们知道CAPACITY可以认为是Worker的最大数量
  00011111 11111111 11111111 11111111
  按位取反之后
  11100000 00000000 00000000 00000000
  然后跟前面存储的线程池的状态和Worker数量的字段ctl去进行按位与运算
  因为我们上面按位取反之后的二进制后面29位都是0,
  所以进行按位与运算的时候,肯定只剩下高位四位(加上符号位),实际上就是我们线程池的状态
4.3.4.1.3.获取Worker线程的数量
  private static int workerCountOf(int c)  { 
        return c & CAPACITY; 
    }
1.因为前面我们说过CAPACITY,二进制内存中   00011111 11111111 11111111 11111111
1.这个理解上就比较简单了,因为我们Worker的数量的高三位都是0,然后CAPACITY,低位都是1
  进行按位与运算之后,相同为1,那么结果为Worker的数量了

4.3.4.2.addWorker(Runnable firstTask, boolean core)解析

		/**
		 * 大家注意下,这里的Worker 其实就是一个线程,这个线程执行的请求的任务
		 *
     * Checks if a new worker can be added with respect to current
     * pool state and the given bound (either core or maximum). If so,
     * the worker count is adjusted accordingly, and, if possible, a
     * new worker is created and started, running firstTask as its
     * first task. This method returns false if the pool is stopped or
     * eligible to shut down. It also returns false if the thread
     * factory fails to create a thread when asked.  If the thread
     * creation fails, either due to the thread factory returning
     * null, or due to an exception (typically OutOfMemoryError in
     * Thread.start()), we roll back cleanly.
     * 翻译:
     * 根据当前线程池的状态和给定的线程池的范围(核心线程池数量和最大的线程池数量)检查是否可以创建新Worker;
     * 如果可以,那么WorkerCount会相应的调整,同时,新创建的Worker会执行我们传递进来的firstTask任务作为
     * 他的第一个任务(这句话,我们可以认为,新创建的Worker实际上就是线程池中一个线程,一旦firstTask任务
     * 结束,实际上这个线程池中Worker线程并不会消亡,他会继续处理新的任务请求);
     * 如果线程池处理停止状态或者SHUTDOWN状态,该方法将返回false,表示创建任务失败;
     * 如果线程创建失败,不管是由于线程工厂返回null(线程创建失败)还是OOM内存溢出导致的异常等,
     * 我们都将彻底回滚当前操作;
     *
     * @param firstTask the task the new thread should run first (or
     * null if none). Workers are created with an initial first task
     * (in method execute()) to bypass queuing when there are fewer
     * than corePoolSize threads (in which case we always start one),
     * or when the queue is full (in which case we must bypass queue).
     * Initially idle threads are usually created via
     * prestartCoreThread or to replace other dying workers.
     *
     * @param core if true use corePoolSize as bound, else
     * maximumPoolSize. (A boolean indicator is used here rather than a
     * value to ensure reads of fresh values after checking other pool
     * state).
     * @return true if successful
     */
    private boolean addWorker(Runnable firstTask, boolean core) {
        retry:
        for (;;) {
            int c = ctl.get();
            int rs = runStateOf(c);

            /**
            
            *1.rs >= SHUTDOWN 说明当前线程不是RUNNING状态
            *2.! (rs == SHUTDOWN &&firstTask == null &&! workQueue.isEmpty())
            *
            * 简单这两种条件:
            *   1.如果当前线程池的状态是RUNNINN状态,可以进行线程的处理
            *   2.如果是SHUTDOWN状态,并且当前任务是空,并且队列中非空,也是可以进行线程的处理
            *   这里线程的处理,就是Worker任务的线程处理
            *   所以下面的if判断是基于上面两种都不是的情况下,直接返回false,不进行线程任务的处理
            */
            // Check if queue empty only if necessary.
            if (rs >= SHUTDOWN &&
                ! (rs == SHUTDOWN &&firstTask == null &&! workQueue.isEmpty()))
                return false;

            for (;;) {
                int wc = workerCountOf(c);//获取当前Worker线程的数量
                //如果当前Worker线程任务已经最大值或者大于临街corePoolSize|maximumPoolSize 
                if (wc >= CAPACITY ||wc >= (core ? corePoolSize : maximumPoolSize))
                    return false;
                //如果Worker线程任务比临界corePoolSize|maximumPoolSize小,那么WorkerCount+1
                if (compareAndIncrementWorkerCount(c))
                    break retry;
                //下面的操作主要是基于我们上面compareAndIncrementWorkerCount
                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 {
            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.add(w);
                        int s = workers.size();
                        if (s > largestPoolSize)
                            largestPoolSize = s;
                        workerAdded = true;
                    }
                } finally {
                    mainLock.unlock();
                }
                if (workerAdded) {
                    //这里启动的时候会去调用Worker的Run方法,本质上是runWorker方法
                    //runWorker见下面分析
                    t.start();
                    workerStarted = true;
                }
            }
        } finally {
            if (! workerStarted)
                addWorkerFailed(w);
        }
        return workerStarted;
    }

4.3.4.3.runWorker方法解析

    /**
     * Main worker run loop.  Repeatedly gets tasks from queue and
     * executes them, while coping with a number of issues:
     *
     * 1. We may start out with an initial task, in which case we
     * don't need to get the first one. Otherwise, as long as pool is
     * running, we get tasks from getTask. If it returns null then the
     * worker exits due to changed pool state or configuration
     * parameters.  Other exits result from exception throws in
     * external code, in which case completedAbruptly holds, which
     * usually leads processWorkerExit to replace this thread.
     *
     * 2. Before running any task, the lock is acquired to prevent
     * other pool interrupts while the task is executing, and then we
     * ensure that unless pool is stopping, this thread does not have
     * its interrupt set.
     *
     * 3. Each task run is preceded by a call to beforeExecute, which
     * might throw an exception, in which case we cause thread to die
     * (breaking loop with completedAbruptly true) without processing
     * the task.
     *
     * 4. Assuming beforeExecute completes normally, we run the task,
     * gathering any of its thrown exceptions to send to afterExecute.
     * We separately handle RuntimeException, Error (both of which the
     * specs guarantee that we trap) and arbitrary Throwables.
     * Because we cannot rethrow Throwables within Runnable.run, we
     * wrap them within Errors on the way out (to the thread's
     * UncaughtExceptionHandler).  Any thrown exception also
     * conservatively causes thread to die.
     *
     * 5. After task.run completes, we call afterExecute, which may
     * also throw an exception, which will also cause thread to
     * die. According to JLS Sec 14.20, this exception is the one that
     * will be in effect even if task.run throws.
     *
     * The net effect of the exception mechanics is that afterExecute
     * and the thread's UncaughtExceptionHandler have as accurate
     * information as we can provide about any problems encountered by
     * user code.
     *
     * @param w the worker
     */
    final void runWorker(Worker w) {
        Thread wt = Thread.currentThread();
        Runnable task = w.firstTask;
        w.firstTask = null;
        w.unlock(); // allow interrupts
        boolean completedAbruptly = true;
        try {
            //这里的worker会一直运行,首先判断当前的firstTask是否为空
            //如果不为空,执行该任务,如果为空,getTask那么去WorkerQueue里拿一个
            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);
        }
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章