自定义线程池

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
package online.orange.blog.web.config;


import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

@Slf4j
@Configuration
public class CustomThreadConfig {

static final int DEFAULT_THREAD_QUEUE_SIZE = 100;
static final int DEFAULT_THREAD_KEEP_ALIVE_TIME = 1000;
static final int DEFAULT_THREAD_LIFE_TIME = 1000;
final String THREAD_POOL_NAME = "orange-blog-";

/**
* setCorePoolSize(coreSize):设置核心线程数(CPU核心数)
* setMaxPoolSize(coreSize * 2):最大线程数为核心线程数的2倍
* setQueueCapacity(DEFAULT_THREAD_QUEUE_SIZE):任务队列容量100
* setKeepAliveSeconds(DEFAULT_THREAD_KEEP_ALIVE_TIME):非核心线程空闲1000秒后回收
* setThreadNamePrefix(THREAD_POOL_NAME):线程名前缀"orange-blog-"
* setWaitForTasksToCompleteOnShutdown(true):应用关闭时等待任务完成
* setAwaitTerminationSeconds(DEFAULT_THREAD_LIFE_TIME):最多等待1000秒
*/
@Bean
public ThreadPoolTaskExecutor OrangeBLogThreadPoolExecutor() {
int coreSize = Runtime.getRuntime().availableProcessors();
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(coreSize);
executor.setMaxPoolSize(coreSize * 2);
executor.setQueueCapacity(DEFAULT_THREAD_QUEUE_SIZE);
executor.setKeepAliveSeconds(DEFAULT_THREAD_KEEP_ALIVE_TIME);
executor.setThreadNamePrefix(THREAD_POOL_NAME);
executor.setWaitForTasksToCompleteOnShutdown(true);
executor.setAwaitTerminationSeconds(DEFAULT_THREAD_LIFE_TIME);
executor.initialize();
log.info("OrangeBLogThreadPoolExecutor init success");
return executor;
}

}