springboot并发线程池和Future使用示例

1.建个线程池

@Configuration
@EnableAsync
public class ThreadPoolTaskConfig {
   
   private static final int corePoolSize = 50;
   private static final int maxPoolSize = 100;
   private static final int keepAliveTime = 10;
   private static final int queueCapacity = 200;
   private static final String threadNamePrefix = "Async-Service-";
   
   @Bean("taskExecutor") // bean的名称,默认为首字母小写的方法名
   public ThreadPoolTaskExecutor getAsyncExecutor(){
      ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
      // 核心线程数(默认线程数)
      executor.setCorePoolSize(corePoolSize);
      // 最大线程数
      executor.setMaxPoolSize(maxPoolSize);
      // 缓冲队列数
      executor.setQueueCapacity(queueCapacity);
      // 允许线程空闲时间(单位:默认为秒)
      executor.setKeepAliveSeconds(keepAliveTime);
      // 线程池名前缀
      executor.setThreadNamePrefix(threadNamePrefix);
      // 线程池对拒绝任务的处理策略
      executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
      // 初始化
      executor.initialize();
      return executor;
   }
}

2. 使用

子线程业务代码

	// 主线程业务代码
	@Override
    public List<Map> selectList(PageRequest pageRequest) {
    	List<Future<List<Map>>> futureList = new ArrayList<>(lines.size());
    	List<Map> mapList = new ArrayList<>();
    	futureList.forEach(f -> {
            try {
                // 主线程等待 获取 子线程 数据
                while (true){
                    if (f.isDone() && !f.isCancelled()) {
                        break;
                    }
                }
                mapList.addAll(f.get());
            } catch (InterruptedException | ExecutionException e) {
                e.printStackTrace();
            }
        });
        return mapList;
    }
	
	// 子线程业务代码
	@Override
    @Async("taskExecutor")
    public Future<List<Map>> buildLineMap(){
    	List<Map> l = new ArrayList<>();
    	// 业务处理。。。。
    	l.add(xxx);
    	return new AsyncResult<>(l);
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值