线程池`基础`

时间:2020-07-13 18:42:05   收藏:0   阅读:76


种类






总结

深入源码,你会发现:这几个方法都调用了ThreadPoolExecutor的构造函数,只要研究ThreadPoolExecutor构造函数就行


补充 Executors类创建的线程池对象多有弊端


区别

submit会返回future,可以从中拿到线程执行结果



属性

corePoolSize
?核心线程数,平时保留的线程数

maximumPoolSize
?最大线程数,当阻塞队列都放不下时,启动的新线程的最大数量

keepAliveTime
?超出核心线程数的那些线程,它们的保留时长

unit
?TimeUnit,线程保留时间的单位

workQueue
BlockingQueue,阻塞队列,存放来不及执行的线程

threadFactory
?ThreadFactory,线程工厂

handler
?RejectedExecutionHandler,饱和策略。


构造方法

public ThreadPoolExecutor(
    int corePoolSize,
    int maximumPoolSize,
    long keepAliveTime,
    TimeUnit unit,
    BlockingQueue<Runnable> workQueue,
    ThreadFactory threadFactory,
    RejectedExecutionHandler handler){}

拒绝策略

实践

springboot配置线程池

@Configuration
public class ThreadPoolTaskConfig {
    @Bean
    public Executor executor() {
?       ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();

        // 可用CPU数量;不小于1
        int core = Runtime.getRuntime().availableProcessors();
        // 核心线程数
        executor.setCorePoolSize(core);
        // 最大线程数**
        executor.setMaxPoolSize(core*2+1);
        // 除核心线程外的线程存活时间**
        executor.setKeepAliveSeconds(3);
        // 默认使用SynchronousQueue,若传值>0,底层队列使用LinkedBlockingQueue
        executor.setQueueCapacity(40);
        // 线程名称前缀
        executor.setThreadNamePrefix("-");
        // 设置拒绝策略
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());

?       return executor;
    }
}
评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!