怎样避免线程池选择失误?

来源:5-6 线程池其实是用来管理线程的工具

仰慕傻瓜帮

2020-09-18

jdk默认提供了几种常用线程池 CacheThreadPool, FixedThreadPool, ScheduledThreadPool, SingleThreadPool。
他们分别适合什么场景,在使用的时候,往往对选择有点模糊?老师也可以结合实际工作的使用情况,说一下哈,感谢!

写回答

1回答

张勤一

2020-09-18

同学你好:

    其实对于线程池的选择,除了要看具体的场景之外,更重要的是经验,毕竟,理论始终是理论,你即使张口就来,但是不实际使用下,你永远都不会知道它有哪些坑,以及它到底是怎样“适应”你的场景的。

    下面,我来说说 JDK 提供的四种线程池,以及它们各自适用的场景:

    newFixedThreadPool:适用于同时处理固定任务数的场景

        固定线程池数量, 核心线程数 = 最大线程数

        任务队列: LinkedBlockingQueue(Integer.MAX_VALUE) 无界队列

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

    newCachedThreadPool:适用于处理小任务

        核心线程数为 0, 最大为 Integer.MAX_VALUE,也就是当任务足够多的时候, 可以无限增加线程. 并且所有的线程空闲超过一段时间(调用 Executors 创建的默认 KeepAlive 为 60s)就会被回收

    任务队列: SynchronousQueue 默认传入参数 fair=false,即处理任务非公平

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

    newSingleThreadExecutor:适用于需要将任务按顺序执行的时候

        单个线程的线程池

        任务队列:LinkedBlockingQueue 同样是无界队列

     public static ExecutorService newSingleThreadExecutor() {
        // 核心线程数=最大线程数=1
        return new FinalizableDelegatedExecutorService
            (new ThreadPoolExecutor(1, 1,
                                    0L, TimeUnit.MILLISECONDS,
                                    new LinkedBlockingQueue<Runnable>()));
    }

    newScheduleThreadPool:更适用于需要延时执行或者定时需求的场景

    固定核心线程数,线程数量不会再增长,maximumPoolSize 这个参数对定时线程池没有作用

    public ScheduledThreadPoolExecutor(int corePoolSize) {
        super(corePoolSize, Integer.MAX_VALUE, 0, NANOSECONDS,
              new DelayedWorkQueue());
    }

    

    我是勤一,致力于将这门课程的问答区打造为 Java 知识体系知识库,Java 知识体系 BBS!共同建造、维护这门课程,我需要每一个你!

4
0

Java实操避坑指南 SpringBoot/MySQL/Redis错误详解

掌握业务开发中各种类型的坑,,Java web开发领域通用

466 学习 · 204 问题

查看课程