-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathThreadPoolConfig.java
More file actions
85 lines (75 loc) · 3.21 KB
/
Copy pathThreadPoolConfig.java
File metadata and controls
85 lines (75 loc) · 3.21 KB
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
package com.yw.dynamicthreadpooltest.config;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.concurrent.*;
/**
* 线程池配置
*
* @author: yuanwen
* @since: 2024/9/18
*/
@Configuration
@EnableConfigurationProperties(ThreadPoolConfigProperties.class)
public class ThreadPoolConfig {
@Bean("threadPollExecutorOne")
public ThreadPoolExecutor dynamicThreadPoolOne(ThreadPoolConfigProperties threadPoolConfigProperties) {
//根据线程池配置参数,设置拒绝策略
RejectedExecutionHandler handler;
switch (threadPoolConfigProperties.getRejectPolicy()) {
//丢弃任务不抛出异常
case "CallerRunsPolicy":
handler = new ThreadPoolExecutor.CallerRunsPolicy();
break;
//丢弃最老的任务,执行新任务
case "DiscardOldestPolicy":
handler = new ThreadPoolExecutor.DiscardOldestPolicy();
break;
//多余的任务交给主线程执行
case "DiscardPolicy":
handler = new ThreadPoolExecutor.DiscardPolicy();
break;
//丢弃任务抛出异常
default:
handler = new ThreadPoolExecutor.AbortPolicy();
}
return new ThreadPoolExecutor(
threadPoolConfigProperties.getCorePoolSize(),
threadPoolConfigProperties.getMaxPoolSize(),
threadPoolConfigProperties.getKeepAliveTime(),
TimeUnit.SECONDS,
new LinkedBlockingDeque<>(threadPoolConfigProperties.getBlockQueueSize()),
Executors.defaultThreadFactory(),
handler);
}
@Bean("threadPollExecutorTwo")
public ThreadPoolExecutor dynamicThreadPoolTwo(ThreadPoolConfigProperties threadPoolConfigProperties) {
//根据线程池配置参数,设置拒绝策略
RejectedExecutionHandler handler;
switch (threadPoolConfigProperties.getRejectPolicy()) {
//丢弃任务不抛出异常
case "CallerRunsPolicy":
handler = new ThreadPoolExecutor.CallerRunsPolicy();
break;
//丢弃最老的任务,执行新任务
case "DiscardOldestPolicy":
handler = new ThreadPoolExecutor.DiscardOldestPolicy();
break;
//多余的任务交给主线程执行
case "DiscardPolicy":
handler = new ThreadPoolExecutor.DiscardPolicy();
break;
//丢弃任务抛出异常
default:
handler = new ThreadPoolExecutor.AbortPolicy();
}
return new ThreadPoolExecutor(
threadPoolConfigProperties.getCorePoolSize(),
threadPoolConfigProperties.getMaxPoolSize(),
threadPoolConfigProperties.getKeepAliveTime(),
TimeUnit.MINUTES,
new LinkedBlockingDeque<>(threadPoolConfigProperties.getBlockQueueSize()),
Executors.defaultThreadFactory(),
handler);
}
}