本文地址:CompletableFuture使用
1、自定义线程池配置类
1 | /* Copyright © 2022 Yuech and/or its affiliates. All rights reserved. */ |
2、自定义线程池
使用CallerRunsPolicy线程池丢弃策略,如果线程池满了,将会交给主线程执行1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55/* Copyright © 2022 Yuech and/or its affiliates. All rights reserved. */
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.task.AsyncTaskExecutor;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.util.concurrent.ThreadPoolExecutor;
/**
* 线程池配置
*
* @author Yuech
* @version 1.0
* @since 2022-11-24 15:57
*/
"common.pool", value = "enabled", matchIfMissing = true) (prefix =
({CommonThreadPoolProperties.class})
"com.yuech.config") (value =
public class CommonThreadPoolConfig {
private CommonThreadPoolProperties properties;
public ThreadPoolTaskExecutor commonAsyncTaskExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
// 核心线程池大小
executor.setCorePoolSize(properties.getCorePoolSize());
// 最大线程数
executor.setMaxPoolSize(properties.getMaxPoolSize());
// 队列容量
executor.setQueueCapacity(properties.getQueueCapacity());
// 活跃时间
executor.setKeepAliveSeconds(properties.getKeepAliveSeconds());
// 线程名字前缀
executor.setThreadNamePrefix(properties.getThreadNamePrefix());
/*
* setRejectedExecutionHandler:当pool已经达到max size的时候,如何处理新任务
* CallerRunsPolicy:不在新线程中执行任务,而是由调用者所在的线程来执行
*/
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
executor.initialize();
return executor;
}
}
3、CompletableFuture调用
1 | package ...; |