线程池个人总结

学习线程池过程中产生的问题

  • 线程池的提交过程是怎么样的
  • 线程池是如何复用的
  • Runnable和Callable提交有什么区别
  • 如何区分核心线程和非核心线程
  • 存活时间到达时如何关闭线程

线程池的提交

线程池的提交有3种方式:

 Future submit(Callable task);
 Future submit(Runnable task, T result);
Future submit(Runnable task);

可以看到分别是2个Runnable和1个Callable的提交,那为什么有两个Runnable的提交呢。通常我们都是认为Runnable和Callable的区别是Callable是可以返回一个结果。其实Runnable也是可以返回结果的,根据参数T result可以看出T result就是返回结果,如果不传,那么默认返回NULL。
接下来进入submit方法

public  Future submit(Callable task) {
    if (task == null) throw new NullPointerException();
    RunnableFuture ftask = newTaskFor(task);
    execute(ftask);
    return ftask;
}
public  Future submit(Runnable task, T result) {
    if (task == null) throw new NullPointerException();
    RunnableFuture ftask = newTaskFor(task, result);
    execute(ftask);
    return ftask;
}
public Future submit(Runnable task) {
    if (task == null) throw new NullPointerException();
    RunnableFuture ftask = newTaskFor(task, null);
    execute(ftask);
    return ftask;
}

这三个方法是先调用newTaskFor得到一个RunnableFuture,再提交执行。

protected  RunnableFuture newTaskFor(Runnable runnable, T value) {
        return new FutureTask(runnable, value);
}
protected  RunnableFuture newTaskFor(Callable callable) {
        return new FutureTask(callable);
}

newTaskFor内构造的FutureTask就是我们用来获取执行状态和结果的适配类了。在FutureTask类内,则是统一适配为Callable,只不过Runnable返回NULL或传入的固定值。
我们再看看ThreadPoolExecutor的执行过程:

public void execute(Runnable command) {
    if (command == null)
        throw new NullPointerException();
    //1、判断是否在核心线程内,如果是则尝试创建核心线程
    int c = ctl.get();
    if (workerCountOf(c) < corePoolSize) {
        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);
    }
    //3、加入队列失败则尝试创建非核心线程,注意第二个参数,在添加任务前要做检测
    //,ture表示检测小于核心线程数,false表示检测小于最大线程数
    else if (!addWorker(command, false))
    //4、执行拒绝策略
        reject(command);
}

很明显,在提交任务的过程中,最重要的就是addWorker这个方法。

private boolean addWorker(Runnable firstTask, boolean core) {
    //1、做各种检测,并且尝试CAS线程数,成功则继续,失败则重试或返回
    retry:
    for (;;) {
        int c = ctl.get();
        int rs = runStateOf(c);

        // Check if queue empty only if necessary.
        if (rs >= SHUTDOWN &&
            ! (rs == SHUTDOWN &&
               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 {
        //2、新建Worker来管理任务的执行,并将Worker添加到workers中管理
        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) {
                //3、终于到执行这一步,直接运行start执行
                t.start();
                workerStarted = true;
            }
        }
    } finally {
        if (! workerStarted)
            addWorkerFailed(w);
    }
    return workerStarted;
}

前面说到,参数boolean core控制添加核心/非核心线程,但是在该方法中只有判断时用到了core,所以如何区分核心/非核心线程呢?答案是不区分,这两兄弟在线程池看起来没有区别,只需要考虑线程数和核心数,最大数就可以。
直接运行start,那么队列里的任务怎么办呢?这在Worker内部解决。Worker是一个实现了Runnable的内部类,它的执行逻辑全部在runWorker内:

final void runWorker(Worker w) {
    Thread wt = Thread.currentThread();
    Runnable task = w.firstTask;
    w.firstTask = null;
    w.unlock(); // allow interrupts
    boolean completedAbruptly = true;
    try {
        //1、循环获取任务,直到没有任务
        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 {
                //2、前置处理,默认空实现
                beforeExecute(wt, task);
                Throwable thrown = null;
                try {
                //3、直接执行run,这样就可以保证不同的逻辑在同一个线程内执行
                    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 {
                    //4、后置处理,默认空实现
                    afterExecute(task, thrown);
                }
            } finally {
                task = null;
                w.completedTasks++;
                w.unlock();
            }
        }
        completedAbruptly = false;
    } finally {
        5、移除Worker
        processWorkerExit(w, completedAbruptly);
    }
}

我们可以猜到,getTask就是从队列内获取任务,当获取不到任务,退出循环后,就移除worker。

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.
        if (rs >= SHUTDOWN && (rs >= STOP || workQueue.isEmpty())) {
            decrementWorkerCount();
            return null;
        }

        int wc = workerCountOf(c);

        // Are workers subject to culling?
        boolean timed = allowCoreThreadTimeOut || wc > corePoolSize;

        if ((wc > maximumPoolSize || (timed && timedOut))
            && (wc > 1 || workQueue.isEmpty())) {
            if (compareAndDecrementWorkerCount(c))
                return null;
            continue;
        }

        try {
            //如果需要判断超时,那么就在keepAliveTime时间后拉取任务,否则就阻塞拉取任务
            Runnable r = timed ?
                workQueue.poll(keepAliveTime, TimeUnit.NANOSECONDS) :
                workQueue.take();
            if (r != null)
                return r;
            timedOut = true;
        } catch (InterruptedException retry) {
            timedOut = false;
        }
    }
}

参数timed代表是否需要判断超时,timedOut代表是否超时。如果当前线程数在核心线程数内并且核心线程允许超时,那么timed就是false,这种情况下只有空队列阻塞和获取到任务返回两种情况;而如果是当前线程数超过核心线程,那么也有两种情况,队列有任务直接获取,队列没有任务在keepAliveTime后再获取一次任务,没有任务就结束执行。

你可能感兴趣的:(java后端)