CompletableFuture指定ThreadPoolTaskExecutor自定义线程池
ThreadPool
A simple C++11 Thread Pool implementation
项目地址:https://gitcode.com/gh_mirrors/th/ThreadPool
免费下载资源
·
CompletableFuture指定ThreadPoolTaskExecutor自定义线程池
前言
用的是springboot
二、使用步骤
1.创建自定义线程池
代码如下:
@Configuration
public class asyncTaskExecutorConfig {
//阻塞队列
private static final int workQueue = 20;
//线程空闲后的存活时长
private static final int keepAliveTime = 30;
//Cpu核数
private static final int CPU_COUNT = Runtime.getRuntime().availableProcessors();
//核心线程数量大小
private static final int corePoolSize = Math.max(2, Math.min(CPU_COUNT - 1, 4));
//线程池最大容纳线程数
private static final int maxPoolSize = CPU_COUNT * 2 + 1;
@Bean("asyncTaskExecutor")
public ThreadPoolTaskExecutor asyncTaskExecutor() {
ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
threadPoolTaskExecutor.setThreadNamePrefix("asyncTaskExecutor-");//线程前缀
threadPoolTaskExecutor.setCorePoolSize(corePoolSize);//核心线程数
threadPoolTaskExecutor.setMaxPoolSize(maxPoolSize);//最大线程数
threadPoolTaskExecutor.setQueueCapacity(workQueue);//等待队列
threadPoolTaskExecutor.setKeepAliveSeconds(keepAliveTime);//线程池维护线程所允许的空闲时间,单位为秒
threadPoolTaskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());// 线程池对拒绝任务(无线程可用)的处理策略
threadPoolTaskExecutor.initialize();
return threadPoolTaskExecutor;
}
}
2.工具类注入线程池
代码如下:
@Autowired
@Qualifier("asyncTaskExecutor")
private ThreadPoolTaskExecutor asyncTaskExecutor;
此处的@Qualifier注解名称为上一步线程池中的bean中定义的名称。
3. 使用
代码如下:
/**
* 异步执行
* @param call
*/
private void async(Runnable call) {
CompletableFuture<Void> runFuture = CompletableFuture.runAsync(call::run, asyncTaskExecutor).exceptionally(e -> {
log.error("当前线程{},异步执行失败", Thread.currentThread().getName(), e);
return null;
});
try {
runFuture.get(30, TimeUnit.SECONDS);
} catch (InterruptedException | ExecutionException | TimeoutException e) {
log.error("当前线程{},异步操作执行失败", Thread.currentThread().getName(), e);
}
}
此处例子只示范了一下无返回值的runAsync方法。
总结
以上如有错误之处请指出,后续改进
GitHub 加速计划 / th / ThreadPool
7.74 K
2.22 K
下载
A simple C++11 Thread Pool implementation
最近提交(Master分支:2 个月前 )
9a42ec13 - 9 年前
fcc91415 - 9 年前
更多推荐
已为社区贡献1条内容
所有评论(0)