JAVA-线程池初始化

日常WEB项目启动前,我们都会基于容器机器配置初始化一个线程池,方便后期多线程任务使用。

线程池配置

@Data
@Configuration
@PropertySource(value = {"classpath:conf/config.properties"})
@ConfigurationProperties(prefix = "spring.thread.pool.common")
public class CommonThreadPoolConfiguration {
    private static final Logger LOGGER = LoggerFactory.getLogger(CommonThreadPoolConfiguration.class);

    private Integer core = 1;

    private Integer max = 5;

    private Integer alive = 200;

    private Integer queue = 100;

    @Bean(name = "commonThreadPoolTaskExecutor")
    public ThreadPoolTaskExecutor commonThreadPoolTaskExecutor() {
        ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
        threadPoolTaskExecutor.setCorePoolSize(core);
        threadPoolTaskExecutor.setMaxPoolSize(max);
        threadPoolTaskExecutor.setQueueCapacity(alive);
        threadPoolTaskExecutor.setKeepAliveSeconds(queue);
        threadPoolTaskExecutor.setThreadNamePrefix("common-pool-");
        LOGGER.info("通用处理线程池初始化参数。 core:{}, max:{}, alive:{}, queue:{}", core, max, alive, queue);
        threadPoolTaskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.AbortPolicy());
        return threadPoolTaskExecutor;
    }
}

配置文件

# 通用线程池配置
spring.thread.pool.common.core=4
spring.thread.pool.common.max=16
spring.thread.pool.common.alive=200
spring.thread.pool.common.queue=2000

线程池的使用

//异步无回调结果
commonThreadPoolTaskExecutor.submit(new XxxCallable(taskParam,cacheService,key));


//同步有回调结果
int partNum = parts+1;
List<ListenableFuture<String>> futureList = new ArrayList<>();
//多线程启动
for (int i = 1; i <= parts; i++) {
    ListenableFuture<String> stringListenableFuture = commonThreadPoolTaskExecutor.submitListenable(new XxxCallable(xx,xx,xx));
    futureList.add(stringListenableFuture);
}
//收集结果
for (ListenableFuture<String> stringListenableFuture : futureList) {
    String s = stringListenableFuture.get();
    if (StringUtils.isNotEmpty(s) && !result.contains(s)) {
        LOGGER.info("xxx add :{}", s);
        result.add(s);
    }
}

猜你喜欢

转载自blog.csdn.net/caryeko/article/details/141229038