java自定义线程池

本文将介绍几种自定义线程池的方式,线程池的好处这里就不多说了。

1.单例全局线程池,设置线程名称,便于查找问题。自定义corePoolSize, maxPoolSize等等,让定义的人能更明白线程池的语义。

package com.expedia.www.ews.content.provider.concurrent;

import com.google.common.util.concurrent.ThreadFactoryBuilder;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.LinkedBlockingDeque;


/**
 * @author <a href="mailto:v-ksong@expedia.com">ksong</a>
 * @Date 9/26/2019 6:02 PM
 */
public final class CustomThreadPoolExecutor {

    private CustomThreadPoolExecutor() {

    }

    private static ThreadFactory namedThreadFactory = new ThreadFactoryBuilder()
            .setNameFormat("Load-hotel-id-mapping-thread-%d")
            .setDaemon(true)
            .build();

    private static final ExecutorService EXECUTOR_SERVICE =
            new ThreadPoolExecutor(16, 20, 1000, TimeUnit.MILLISECONDS, new LinkedBlockingDeque<>(), namedThreadFactory);

    public static ExecutorService getExecutor() {
        return EXECUTOR_SERVICE;
    }
}

2.使用Spring的方式,Spring基于java的ThreadPoolExecutor封装的ThreadPoolTaskExecutor ,此种方式下线程池的生命周期与Spring上下文的生命周期一致,也是单例全局线程池。

@Bean(name = "hintStepsExecutor")
    public ThreadPoolTaskExecutor hintsTasksExecutor() {
        ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
        threadPoolTaskExecutor.setCorePoolSize(50);
        threadPoolTaskExecutor.setMaxPoolSize(50);
        threadPoolTaskExecutor.afterPropertiesSet();
        return threadPoolTaskExecutor;
    }

3.使用Executors类下的newFixedThreadPool()等静态工厂方法。

ExecutorService executorService = Executors.newFixedThreadPool(10);
executorService.submit(() -> System.out.println("Execute..."));

最后再说一点:我们什么时候选择单例全局的线程池,什么时候选择局部线程池。个人觉得这两种线程池都有各自的使用场景。

1.全局线程池一旦创建就不要关闭,否则将会不可用。全局线程池的线程资源会一直存在,一直占用资源。

2.局部线程池的好处是可以用完就释放资源,不用长期占用资源。最后要记得优雅地关闭线程池,否则会出现内存泄漏之类的问题。至于如何优雅地关闭线程池,请读者自行百度了,我在这里先偷个懒。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值