本文主要是介绍记CompletableFuture在项目中的实际用法,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
1.在application.yaml中记录线程池配置信息
thread:coreSize: 20maxSize: 200keepAliveTime: 20
2.在MyThreadConfig配置类中映射线程池配置信息
@Configuration
public class MyThreadConfig {@Value("thread.coreSize")private Integer coreSize;@Value("thread.maxSize")private Integer maxSize;@Value("thread.keepAliveTime")private Integer keepAliveTime;@Beanpublic ThreadPoolExecutor threadPoolExecutor() {return new ThreadPoolExecutor(coreSize,maxSize,keepAliveTime,TimeUnit.SECONDS,new LinkedBlockingDeque<>(2000),new CustomizableThreadFactory("CPool"),// setRejectedExecutionHandler:当pool已经达到max size的时候,如何处理新任务// CallerRunsPolicy:不在新线程中执行任务,而是由调用者所在的线程来执行new ThreadPoolExecutor.CallerRunsPolicy());}}
3.实际代码中使用CompletableFuture
@Resourceprivate ThreadPoolExecutor executor;RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();CompletableFuture<Long> pickupTask = CompletableFuture.supplyAsync(() -> {RequestContextHolder.setRequestAttributes(requestAttributes);// 处理业务逻辑return 0L;}, executor).whenComplete((res, error) -> {if (error != null) {log.error(error.getMessage());}});CompletableFuture<Long> deliverTask = CompletableFuture.supplyAsync(() -> {RequestContextHolder.setRequestAttributes(requestAttributes);// 处理业务逻辑return 0L;}, executor).whenComplete((res, error) -> {if (error != null) {log.error(error.getMessage());}});CompletableFuture<Long> waitTask = CompletableFuture.supplyAsync(() -> {RequestContextHolder.setRequestAttributes(requestAttributes);// 处理业务逻辑return 0L;}, executor).whenComplete((res, error) -> {if (error != null) {log.error(error.getMessage());}});CompletableFuture.allOf(pickupTask, deliverTask, waitTask).join();
CustomizableThreadFactory.java
public class CustomizableThreadFactory implements ThreadFactory {private final ThreadGroup group;private final AtomicInteger threadNumber = new AtomicInteger(1);private final String namePrefix;public CustomizableThreadFactory(String prefix) {this.namePrefix = "ThreadPool-" + prefix + "-thread-";SecurityManager s = System.getSecurityManager();group = (s != null) ? s.getThreadGroup() :Thread.currentThread().getThreadGroup();}@Overridepublic Thread newThread(Runnable r) {Thread t = new Thread(group, r,namePrefix + threadNumber.getAndIncrement(),0);if (t.isDaemon()) {t.setDaemon(false);}if (t.getPriority() != Thread.NORM_PRIORITY) {t.setPriority(Thread.NORM_PRIORITY);}return t;}
}
这篇关于记CompletableFuture在项目中的实际用法的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!