CompletableFuture使用IOC容器中自定义线程池

CompletableFuture使用IOC容器中自定义线程池

  • 开启Spring对异步方法的支持
@EnableAsync
@SpringBootApplication
public class ThreadDemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(ThreadDemoApplication.class, args);
    }

}
  • 创建自定义线程池,并交给ioc容器管理
@Configuration
public class ThreadPoolConfig {


    @Bean
    public Executor asyncServiceExecutor(){
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(8);
        executor.setMaxPoolSize(10);
        executor.setQueueCapacity(100);
        executor.setKeepAliveSeconds(60);
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        executor.setThreadNamePrefix("qzzThread");
        executor.initialize();
        return executor;
    }
}
  • 新建一个类,使用@Autowired配合@Qualifier注解注入我们自定义线程池
@Component
@Async		//该类下所有方法都会另起线程执行
public class MyTest {
    
    
    @Autowired
    @Qualifier("asyncServiceExecutor")	//注入指定名称的bean
    private Executor executor;
    
    
    public CompletableFuture<String> future() throws Exception {
        CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
            System.err.println(Thread.currentThread().getName() + ":执行了");
            return "1号选手";
        }, executor).whenComplete((res, e) -> {
            System.err.println(Thread.currentThread().getName() + ":2执行了");
            res += "--2号选手";
            System.err.println(res + "-" + e);
        });
        System.err.println(future.get());
        return future;
    }
    
}
  • 最终效果

image

posted @   姜晓姜晓  阅读(248)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
点击右上角即可分享
微信分享提示