测试老兵 线程数合理评估

CC · February 28, 2019 · 510 hits

0x01 来自面试题

100~10000 的短任务 (3 秒),半个小时完成,线程池起多少个线程比较合适?用哪个线程池实例对象

0x02 分析

一个线程半个小时内最多可完成多少任务计算: 30*60/3 = 600 个任务
对应的最大线程数: 10000/600 = 16.7 个线程
对应的 100 个短任务,按照计算只需一个线程即可

0x03 继续

使用 ThreadPoolExecutor 进行创建,corePoolSize 设置为 3,maximumPoolSize 设置为 20,keepAliveTime 设置为 5 秒
再考虑下 当前任务是 IO 密集型 (2n+1) 的还是计算密集型的 (1.8 之前 n+1), 计算出对应的 CPU 核数

0x04 简单代码

public static void main(String[] args) {
        int corePoolSize = 3;
        int maximumPoolSize = 20;
        long keepAliveTime = 5;

        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(corePoolSize, maximumPoolSize,
                keepAliveTime, TimeUnit.MILLISECONDS,
                new LinkedBlockingQueue<Runnable>());
        threadPoolExecutor.execute(new Runnable() {
            @Override
            public void run() {

            }
        });
    }

0x05 代码扩展

ExecutorService executorService = Executors.newCachedThreadPool();
实际调用的就是 ThreadPoolExecutor类方法只是默认做了一层封装

    public static ExecutorService newFixedThreadPool(int nThreads, ThreadFactory threadFactory) {
        return new ThreadPoolExecutor(nThreads, nThreads,
                                      0L, TimeUnit.MILLISECONDS,
                                      new LinkedBlockingQueue<Runnable>(),
                                      threadFactory);
    }
如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!
No Reply at the moment.
需要 Sign In 后方可回复, 如果你还没有账号请点击这里 Sign Up