Java 新建线程时使用线程池处理

说明:

 

  线程池不允许使用Executors去创建,而是通过ThreadPoolExecutor的方式,这样的处理方式让写的同学更加明确线程池的运行规则,规避资源耗尽的风险。 Executors各个方法的弊端:

 

  • newFixedThreadPoolnewSingleThreadExecutor:

    主要问题是堆积的请求处理队列可能会耗费非常大的内存,甚至OOM。

 

  • newCachedThreadPoolnewScheduledThreadPool:

    主要问题是线程数最大数是Integer.MAX_VALUE,可能会创建数量非常多的线程,甚至OOM。

 

  Executors 中各个线程解释链接:https://blog.csdn.net/qq_36381855/article/details/79942555
---------------------

  推荐使用一下两种:

  • ThreadPoolExecutor 创建线程池
    public class ThreadPoolTest {
    
        private volatile static ExecutorService executorService;
    
        public static ExecutorService getExecutorService() {
    
            if (executorService == null) {
                synchronized (ThreadPoolTest.class) {
                    /**
                     * 使用谷歌的guava框架
                     * ThreadPoolExecutor参数解释
                     *   1.corePoolSize 核心线程池大小
                     *   2.maximumPoolSize 线程池最大容量大小
                     *   3.keepAliveTime 线程池空闲时,线程存活的时间
                     *   4.TimeUnit 时间单位
                     *   5.ThreadFactory 线程工厂
                     *   6.BlockingQueue任务队列
                     *   7.RejectedExecutionHandler 线程拒绝策略
                     */
                    ThreadFactory namedThreadFactory = new ThreadFactoryBuilder().setNameFormat("demo-pool-%d").build();
                    executorService = new ThreadPoolExecutor(10, 20,
                            0L, TimeUnit.MILLISECONDS,
                            new LinkedBlockingQueue<Runnable>(1024), namedThreadFactory, new ThreadPoolExecutor.AbortPolicy());
    
                }
            }
            return executorService;
        }
    }

 

  • ThreadPoolTaskExecutor 创建线程池
        public Executor getAsyncExecutor() {
            ThreadPoolTaskExecutor threadPool = new ThreadPoolTaskExecutor();
            // 设置核心线程数
            threadPool.setCorePoolSize(5);
            // 设置最大线程数
            threadPool.setMaxPoolSize(10);
            // 线程池所使用的缓冲队列
            threadPool.setQueueCapacity(25);
            // 设置线程活跃时间(秒)
            threadPool.setKeepAliveSeconds(60);
            // 等待所有任务结束后再关闭线程池
            threadPool.setWaitForTasksToCompleteOnShutdown(true);
            // 线程名称前缀
            threadPool.setThreadNamePrefix("");
            // 初始化线程
            threadPool.initialize();
            return threadPool;
        }

     

 

--------------------- 

原文:https://blog.csdn.net/more_try/article/details/81506501 

转载于:https://www.cnblogs.com/BestWishesZJ/p/10305179.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值