java线程池源码浅析

java.util.concurrent.Executors 创建线程池常用封装类,不过一般不推荐使用。因为很多线程池参数无法定制化。

java.util.concurrent.ThreadPoolExecutor 推荐直接使用线程池创建类。参数构造一目了然。

创建线程池构造参数详解

corePoolSize 核心线程数,只要线程池中有效线程数小于这个值,执行任务时直接创建线程并运行
maximumPoolSize 线程池允许创建的最大线程数
keepAliveTime 多余空闲线程数最大存活时间,一旦超过直接回收。这里通过阻塞队列的带有超时时间poll方法实现
unit 超时时间单位
workQueue 工作队列,尚未执行的任务会先丢进工作队列
threadFactory 创建线程的工程类,可以自定义工程类实现线程名生成规则的自定义
handler 线程解决策略,默认是向外层抛异常处理
allowCoreThreadTimeOut 注,构造器没有对此参数的初始化,默认为false即不对核心线程数进行回收,设置为true即为超过存活时间核心线程数也进行回收

 

线程池主要参数详解

runstate 当前线程池运行状态,有下面几个状态:

    running运行状态, 接受新任务和处理队列中的任务

    shundown关闭状态,不接收新任务,但是还要处理队列中的任务

    stop停止状态, 不接受新任务,也不处理队列中的任务

    tidying过渡状态,  所有任务被中断,workcount为0,然后过渡到tidying状态

    terminated中止状态 终端状态

workercount 当前线程池有效线程数

ctl 线程池控制状态,默认运行状态,由上面runstate和workercount按位或产生

 

提交任务主要代码块如下:

        int c = ctl.get();
        if (workerCountOf(c) < 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);

 

 如上分三步走

1.  当前池中线程数少于核心线程数,直接添加任务

2. 线程池处于运行状态下,直接把任务丢进工作队列里,这里有个double check防止线程池不在运行状态。 如果当前线程数没有了即都被回收掉了,重新创建。

3. 工作队列已满,直接创建线程执行任务,若创建失败,执行拒接策略

 

创建线程任务部分代码

    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 &&
                   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 {
            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) {
                    t.start();
                    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 {
            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);
        }
    }

 

这里需要注意的是getTask()方法,主要是从工作队列里取执行任务。

    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 {
                Runnable r = timed ?
                    workQueue.poll(keepAliveTime, TimeUnit.NANOSECONDS) :
                    workQueue.take();
                if (r != null)
                    return r;
                timedOut = true;
            } catch (InterruptedException retry) {
                timedOut = false;
            }
        }
    }

这里需要特别注意, workQueue.poll(keepAliveTime,TimeUnit.NANOSECONDS)和workQueue.take()的使用

 

线程池关闭操作

shutdown() 尝试关闭,只是尝试获取每个工作线程的锁然后终端线程,并不保证一定会关闭
shutdownNow() 强制关闭,强制中断线程,但如果线程无法中断,也是无法强制关闭的,一般不会出现此问题
awaitTermination() 等待线程池进入中止状态。一般上述两个关闭最好在配合此等待方法使用

 

你可能感兴趣的:(java线程池源码浅析)