java线程池的那些事

多线程开发越来越常见,开发者常常使用多线程完成一些耗时操作,通过并发来提高系统的响应速度。尤其是在Android移动端开发,为了提升用户体验,常常将一些操作放在异步线程中完成。但是,如果一味滥用多线程,会造成系统资源浪费,而且常常会出现并发问题。因此线程的管理就是一个非常重要的事,线程池也就应运而生。

线程池使用意义:

1)降低系统资源的消耗,线程池中实现线程的复用技术减少无限量的线程创建,减少线程创建和销毁带来的资源浪费;
2)提高响应速度,当有异步任务需要执行时,若线程中有空闲线程存在那么可以快速响应,无需新创建线程;
3)提高线程的可管理性,线程本身是一种稀缺资源,无节制的创建线程除了会造成资源浪费,而且会降低系统稳定性,带来许多并发问题。线程池对线程进行统一的管理、分配。
线程池的好处已经显而易见,若是系统中频繁创建线程来执行任务可以采用线程池技术;反之,若频率相对较低也不需要强行使用线程池。总体而言,根据系统的设计来定方案。

线程池的使用:

1、创建线程池,解析其构造函数:
    /**
     * Creates a new {@code ThreadPoolExecutor} with the given initial
     * parameters.
     *
     * @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 threadFactory the factory to use when the executor
     *        creates a new thread
     * @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 threadFactory} or {@code handler} is null
     */
    public ThreadPoolExecutor(int corePoolSize,
                              int maximumPoolSize,
                              long keepAliveTime,
                              TimeUnit unit,
                              BlockingQueue<Runnable> workQueue,
                              ThreadFactory threadFactory,
                              RejectedExecutionHandler handler) {
        if (corePoolSize < 0 ||
            maximumPoolSize <= 0 ||
            maximumPoolSize < corePoolSize ||
            keepAliveTime < 0)
            throw new IllegalArgumentException();
        if (workQueue == null || threadFactory == null || handler == null)
            throw new NullPointerException();
        this.corePoolSize = corePoolSize;
        this.maximumPoolSize = maximumPoolSize;
        this.workQueue = workQueue;
        this.keepAliveTime = unit.toNanos(keepAliveTime);
        this.threadFactory = threadFactory;
        this.handler = handler;
    }

1)corePoolSize(核心线程数):可以理解为线程池的基本线程数量,正常情况下,如果线程池的线程数量小于核心线程数,当有任务提交到线程池执行时,会直接创建一个线程执行。当线程数量大于等于corePoolSize时便不再直接创建线程。
2)maximumPoolSize(最大线程数):线程池可以容纳的最大线程数量,当线程池中的线程数量大于等于maximumPoolSize时便交给饱和策略,不可以再创建新的线程。
3)keepAliveTime(线程保留时间):线程池的工作线程执行完任务后,可以保留空闲状态的时间,用于控制空闲线程的保存时间。当线程数量小于等于corePoolSize时,该时间设置之后无用。
4)unit(保留时间单位):线程存活时间的单位。天、小时、分、秒等。
5)workQueue(任务队列):用于保存等待执行任务的阻塞队列。可以选择以下集中队列:
ArrayBlockingQueue:基于数组实现的有界阻塞队列,遵循FIFO原则;
LinkedBlockingQueue:基于链表实现的有界阻塞队列,遵循FIFO原则。吞吐量高于ArrayBlockingQueue。Executors.newFixedThreadPool()使用该队列。

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

SynchronousQueue:不存储元素的阻塞队列,每当任务想要插入时,就会进入阻塞状态,只有等到另外一个线程调用移除操作才会被唤醒。吞吐量高于LinkedBlockingQueue,Executors.newCachedThreadPool()使用该队列。

    public static ExecutorService newCachedThreadPool() {
        return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
                                      60L, TimeUnit.SECONDS,
                                      new SynchronousQueue<Runnable>());
    }

PriorityBlockingQueue:具有优先级的无限阻塞队列。

6)threadFactory(线程工厂):用于创建线程工厂类,通常情况下可以不指定,因为有另外一个构造方法指定类默认的线程工厂,Executors.defaultThreadFactory()。

    static class DefaultThreadFactory implements ThreadFactory {
        private static final AtomicInteger poolNumber = new AtomicInteger(1);
        private final ThreadGroup group;
        private final AtomicInteger threadNumber = new AtomicInteger(1);
        private final String namePrefix;

        DefaultThreadFactory() {
            SecurityManager s = System.getSecurityManager();
            group = (s != null) ? s.getThreadGroup() :
                                  Thread.currentThread().getThreadGroup();
            namePrefix = "pool-" +
                          poolNumber.getAndIncrement() +
                         "-thread-";
        }

        public Thread newThread(Runnable r) {
            Thread t = new Thread(group, r,
                                  namePrefix + threadNumber.getAndIncrement(),
                                  0);
            if (t.isDaemon())
                t.setDaemon(false);
            if (t.getPriority() != Thread.NORM_PRIORITY)
                t.setPriority(Thread.NORM_PRIORITY);
            return t;
        }
    }

7)handler(饱和处理策略):当线程池的工作队列已满,而且线程数大于等于maximumPoolSize时,若再提交新的任务,则会将其交给饱和策略处理。java中提供了几种处理策略,默认策略为AbortPolicy。
AbortPolicy:直接抛出异常。
CallerRunsPolicy:只用调用者所在线程来运行任务。
DiscardOldestPolicy:丢弃队列中最近的一个任务,并执行当前任务。
DiscardPolicy:不处理,不丢弃。

2、向线程池提交任务:

execute()方法:

        threadPoolExecutor.execute(new Runnable() {
            @Override
            public void run() {
                System.out.println("run task by execute");
            }
        });

submit()方法:

        Future<?> future = threadPoolExecutor.submit(new Runnable() {
            @Override
            public void run() {
                System.out.println("run task by submit");
            }
        });

上述2个方法均可以向线程池提交任务,其最大区别在于是否需要返回值。execute方法没有返回值,submit方法会返回一个Future对象,该对象可以获取任务执行的结果。

3、线程池关闭:

线程池关闭是通过遍历线程中所有的工作线程,然后逐个调用线程的interrupt方法中断线程,因此并不能保证所有线程都能停止,不响应中断的任务则无法终止。
1)shutdown():将线程池的状态设置成SHUTDOWN状态,然后中断所有没有执行任务的线程(中断空闲线程)
2)shutdownNow():将线程池的状态设置成STOP状态,尝试停止所有正在执行或者暂停任务的线程(所有线程),并返回等待执行任务的列表。

线程池原理分析:

流程图

源码解析:
    /**
     * 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();
        //判断当前线程数量是否小于核心线程数量
        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);
        }
    }

    /**
     * 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.
     *
     * @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);

            // 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;
    }

     Work类中最终执行任务的方法
    /**
     * 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 {
            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);
        }
    }

结束语

相信大家阅读此文之后,对于线程池技术有了一定的了解。与其他技术一样,大家只有在实践中才能真正体会到其妙处,当你感受到之后再回过头去理解它的设计原理便会更加清晰。如果有兴趣可以读一下《java并发编程的艺术》这本书,书中的讲解比文章会更加详细。

猜你喜欢

转载自blog.csdn.net/hb_csu/article/details/80659784