平时在使用线程池时,更多关注到的是coreSize、maxSize、blockQueue、RejectedExecutionHandler这些参数,但在线程池监控领域,还需要关注到其他的一些方法。在此处做统一记录和备忘:

public static void main(String[] args) {

    ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(2, 5, 1, TimeUnit.MINUTES, new ArrayBlockingQueue<>(1024), new ThreadPoolExecutor.CallerRunsPolicy());

    // 启动所有核心线程(预热)
    threadPoolExecutor.prestartAllCoreThreads();
    // 启动一个核心线程
    threadPoolExecutor.prestartCoreThread();

    // 默认情况下构造器中的keepAliveTime指定的是非核心线程的空闲时间, 通过如下方法, 可以允许核心线程超时
    threadPoolExecutor.allowCoreThreadTimeOut(true);

    // ⭐️ 动态线程池必备方法
    // 启动后, 设置核心线程数量
    threadPoolExecutor.setCorePoolSize(3);
    // 启动后, 设置最大线程数量
    threadPoolExecutor.setMaximumPoolSize(10);
    // 已执行完的任务总数
    threadPoolExecutor.getTaskCount();
    // 获取工作队列剩余数量
    threadPoolExecutor.getQueue().remainingCapacity();
    }

后记

通过上面的代码可知,在运行过程中我们也是可以操作coreSizemaxSize的。那么如何才能实现对Queue的大小进行控制呢?目前开源届常用的是采取RabbitMQ中的VariableLinkedBlockingQueue来实现。