08 线程池

2019-08-19  本文已影响0人  攻城狮哦哦也

1 线程池概述

1.1 什么是线程池

线程池就是提前创建若干个线程,如果有任务需要处理,线程池里的线程就会处理任务,处理完之后线程并不会被销毁,而是等待下一个任务。由于创建和销毁线程都是消耗系统资源的,所以当你想要频繁的创建和销毁线程的时候就可以考虑使用线程池来提升系统的性能。

1.2 为什么要用线程池

2 JDK中的线程池

ThreadPoolExecutor,jdk所有线程池实现的父类

2.1 构造方法

图片.png

2.2 参数说明

属性 描述
int corePoolSize 线程池中核心线程数,< corePoolSize ,就会创建新线程,= corePoolSize ,这个任务就会保存到BlockingQueue,如果调用prestartAllCoreThreads()方法就会一次性的启动corePoolSize 个数的线程。
int maximumPoolSize 允许的最大线程数,BlockingQueue也满了,< maximumPoolSize时候就会再次创建新的线程
long keepAliveTime 线程空闲下来后,存活的时间,这个参数只在> corePoolSize才有用
TimeUnit unit 存活时间的单位值
BlockingQueue<Runnable> workQueue 保存任务的阻塞队列
ThreadFactory threadFactory 创建线程的工厂,给新建的线程赋予名字
RejectedExecutionHandler handler 饱和策略;AbortPolicy:直接抛出异常,默认;CallerRunsPolicy:用调用者所在的线程来执行任务;DiscardOldestPolicy:丢弃阻塞队列里最老的任务,队列里最靠前的任务;DiscardPolicy:当前任务直接丢弃;实现自己的饱和策略,实现RejectedExecutionHandler接口即可

2.3 任务提交方法

提交任务
ThreadPoolExecutor:execute(Runnable command) 不需要返回
Future<T>:submit(Callable<T> task) 需要返回

2.4 关闭线程池

shutdown(),shutdownNow();
shutdownNow():设置线程池的状态,还会尝试停止正在运行或者暂停任务的线程
shutdown():设置线程池的状态,只会中断所有没有执行任务的线程

3 线程池工作原理

3.1 流程机制

图片.png
1:当线程池线程数量 < corePoolSize,就在线程池中新建一个线程
2:当线程池线程数量 >= corePoolSize,将线程放入阻塞队列,当corePool中有线程释放后,在从队列中取线程
3:当阻塞队列的线程已满并且线程数 < maximumPoolSize,则在线程池中新建线程
4:线程数 > maximumPoolSize则执行饱和策略

3.2 源码逻辑

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) {//线程数量小于corePoolSize,新建线程
            if (addWorker(command, true))
                return;
            c = ctl.get();
        }
        if (isRunning(c) && workQueue.offer(command)) {//offer(command)队列中放入任务,失败返回false
            int recheck = ctl.get();
            if (! isRunning(recheck) && remove(command))
                reject(command);
            else if (workerCountOf(recheck) == 0)
                addWorker(null, false);
        }
        else if (!addWorker(command, false))//线程数量小于maximumPoolSize,创建新线程
            reject(command);//拒绝新任务
    }

4 合理配置线程池

根据任务的性质来:计算密集型(CPU),IO密集型,混合型

4.1 计算密集型:

例如加密,大数分解,正则……., 线程数适当小一点,最大推荐:机器的Cpu核心数+1,为什么+1,防止页缺失,(机器的Cpu核心=Runtime.getRuntime().availableProcessors();)

4.2 IO密集型:

例如读取文件,数据库连接,网络通讯, 线程数适当大一点,机器的Cpu核心数*2,

4.3 混合型:

尽量拆分,IO密集型~计算密集型,拆分提高效率明显
IO密集型>>计算密集型,拆分意义不大

4.4 队列选择

队列的选择上,应该使用有界,无界队列可能会导致内存溢出,OOM

5 预定义的线程池

预定义的线程池内部其实就是调用了ThreadPoolExecutor的构造方法,只不过通过参数来控制自身的特性,若果技术能力允许的话,建议开发者在调用线程池时直接用ThreadPoolExecutor类来创建,因为很多的预定义线程池都使用了无界队列,而使用无界队列可能会导致内存溢出,OOM等异常。
newFixedThreadPool
创建固定线程数量的,适用于负载较重的服务器,使用了无界队列

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

newSingleThreadExecutor
创建单个线程,需要顺序保证执行任务,不会有多个线程活动,使用了无界队列

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

newCachedThreadPool
会根据需要来创建新线程的,执行很多短期异步任务的程序,使用了SynchronousQueue

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

其实上述几个线程池都是内部调用了ThreadPoolExecutor类的构造方法
WorkStealingPool(JDK7以后)
基于ForkJoinPool实现
ScheduledThreadPoolExecutor

上一篇 下一篇

猜你喜欢

热点阅读