springboot简单的使用多线程

springboot简单的使用多线程


配置类

package com.enation.app.oupin.buyer.api.goods;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.ThreadPoolExecutor;

@Configuration
@EnableAsync//开启异步调用
public class GlobalConfig {
    @Bean
    public ThreadPoolTaskExecutor defaultThreadPool(){
        ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
        //核心线程数量
        threadPoolTaskExecutor.setCorePoolSize(5);
        //最大线程数量
        threadPoolTaskExecutor.setMaxPoolSize(20);
        //队列中最大任务数
        threadPoolTaskExecutor.setQueueCapacity(20);
        //线程名称前缀
        threadPoolTaskExecutor.setThreadNamePrefix("ThreadPool-");
        //当达到最大线程数时如何处理新任务
        threadPoolTaskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        //线程空闲后最大存活时间
        threadPoolTaskExecutor.setKeepAliveSeconds(60);
        //初始化线程池
        threadPoolTaskExecutor.initialize();
        return threadPoolTaskExecutor;
    }
}

注入

 @Autowired
    private ThreadPoolTaskExecutor threadPoolTaskExecutor;

多线程调用


                threadPoolTaskExecutor.execute(new Runnable() {

                   // @SneakyThrows
                    @Override
                    public void run() {

                        goodsIndexManager.addIndex(goods);

                        //Thread.sleep(1000);
                    }
                });

你可能感兴趣的:(java)