1、@Bean方式创建线程池并注入容器

/**
 * FileName: com.XXX.cloud.datas.config
 * Author: XXX
 * Date: 2019/7/4 13:36
 * Description: 线程池
 * History:
 * <author>          <time>          <version>          <desc>
 * 作者姓名           修改时间           版本号              描述
 */
package com.XXX.cloud.datas.config;

import com.google.common.util.concurrent.ThreadFactoryBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;

import java.util.concurrent.*;

/**
 * @Description: 线程池配置
 * @ClassName: ThreadExecutorConfig
 * @Author: XXX
 * @Date: 2019/7/4 13:36
 * @Version: 1.0
 */
@Configuration
@EnableAsync
public class ThreadExecutorConfig {

    private static final Logger logger = LoggerFactory.getLogger(ThreadExecutorConfig.class);

    /**
     * 核心线程数
     */
    private int corePoolSize = Runtime.getRuntime().availableProcessors();
    /**
     * 最大线程数
     */
    private int maxPoolSize = Integer.MAX_VALUE;
    /**
     * 线程销毁时间
     */
    private Long keepAliveTime = 60L;
    /**
     * 任务队列
     */
    private SynchronousQueue synchronousQueue = new SynchronousQueue<>();
    /**
     * 线程名称
     */
    private ThreadFactory namedThreadFactory = new ThreadFactoryBuilder().setNameFormat("datas-thread-%d").build();

    @Bean
    public ExecutorService myDataThreadPool() {
        logger.info("线程池创建===>开始");
        /**
         * 创建线程池
         * Runtime.getRuntime().availableProcessors()
         */
        ExecutorService threadPool = new ThreadPoolExecutor(corePoolSize, maxPoolSize, keepAliveTime, TimeUnit.SECONDS, synchronousQueue, namedThreadFactory);
        logger.info("线程池创建===>结束");
        return threadPool;
    }
}

2、在service中注入线程池

@Resource(name = "myDataThreadPool")
private ExecutorService threadPool;

3、创建内部类(也可以不使用内部类)以及子线程调用方法

/**
  * 任务1->创建数据库(多线程返回值)
  * @author XXX
  * @date 2019/5/31 16:40
  * @version 1.0
  */
class MyCallable implements Callable {
    private Long appRunDbType;
    private Long companyId;
    private Long userId;
    public MyCallable(Long appRunDbType, Long companyId, Long userId) {
        this.appRunDbType = appRunDbType;
        this.companyId = companyId;
        this.userId = userId;
    }
    @Override
    public Object call() throws Exception {
        return synchrCreateDb(appRunDbType, companyId, userId);
    }
}
/**
  * 同步方法创建库
  * @author XXX
  * @date 2019/6/13 16:24
  * @version 1.0
  */
public String synchrCreateDb(Long appRunDbType, Long companyId, Long userId) {
     XXX...
}

4、 提交任务到线程池

public String createDb(Long appRunDbType,Long userId,Long companyId) {
    // 创建具有返回值的线程任务
    MyCallable myCallable = new MyCallable(appRunDbType, companyId, userId);
    // 执行任务并获取Future对象
    Future future = threadPool.submit(myCallable);
    try {
        // 从Future对象上获取任务的返回值,并返回
        return future.get().toString();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

 

Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐