一、ThreadPoolExecutor------线程池
private static final ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(30, 30, 30, TimeUnit.SECONDS, new LinkedBlockingQueue<>(60), new ThreadPoolExecutor.AbortPolicy());
static {
threadPoolExecutor.allowCoreThreadTimeOut(true);
}
System.out.println("======start=======");
threadPoolExecutor.execute(() -> {
System.out.println("=============");
});
System.out.println("=========end========");

//异步执行操作

参考资料:https://blog.csdn.net/qq_25806863/article/details/71126867

二、CompletableFuture----获取结果

CompletableFuture<Integer> result = CompletableFuture.supplyAsync(() -> {C
System.out.println("==========2=========");
return 1;
});
CompletableFuture<Integer> res = CompletableFuture.supplyAsync(() -> {
return 2;
}); Integer x = result.get();
Integer y = res.get();
三、异步工具类
public interface AsyncToolCommon {
/**
* 异步执行一个无参无返回值的方法
* @param voidFunction
* @throws Exception
*/
void asyncFunction(VoidFunction voidFunction); /**
* 异步执行一个无参有返回值的方法
* @param supplier
*/
<T> void asyncSupplier(Supplier<T> supplier);
}
@Service
public class AsyncToolCommonImpl implements AsyncToolCommon {
private static final Logger logger = LoggerFactory.getLogger(AsyncToolCommonImpl.class); private static final ForkJoinPool forkJoinPool = new ForkJoinPool(2 * Runtime.getRuntime().availableProcessors() + 1); /**
* 异步执行一个无参无返回值的方法
*
* @param voidFunction
* @throws Exception
*/
@Override
public void asyncFunction(VoidFunction voidFunction) {
CompletableFuture.supplyAsync(() -> {
try {
voidFunction.execute();
return ResultEnum.SUCCESS.getCode();
} catch (Exception e) {
logger.error("asyncExecute error:{}", e);
throw new RuntimeException(e);
}
}, forkJoinPool);
} /**
* 异步执行一个无参有返回值的方法
*
* @param supplier
*/
@Override
public <T> void asyncSupplier(Supplier<T> supplier) {
CompletableFuture.supplyAsync(() -> supplier.get(), forkJoinPool);
} }
@FunctionalInterface
public interface VoidFunction {
/**
* 无参构造体
*/
void execute() throws Exception;
}
asyncToolCommon.asyncFunction(() -> .....);

四、循环调用
List<CompletableFuture<Integer>> futureList = Lists.newArrayList();
for(int i=0;i<10;i++){
futureList.add(CompletableFuture.supplyAsync(() -> {C
System.out.println("==========2=========");
return 1;
});)
}
int count = 0;
for (CompletableFuture<Integer> future : futureList) {
Integer i = future.get(600, TimeUnit.MILLISECONDS);
count += i;
}

五、Fork/Join
//线程池
private ForkJoinPool facePlatFormForkJoinPool = new ForkJoinPool(20);
private ForkJoinPool faceInfoForkJoinPool = new ForkJoinPool(20);
Callable<SearchResultJson> facePlatformCallable = () -> faceService.search(img, searchReq.getClientName(), searchReq.getClientIp(), finalAppSecret, finalToken);
//回调执行结果
Future<SearchResultJson> facePlatFormFuture =facePlatFormForkJoinPool.submit(facePlatformCallable);
SearchResultJson facePlatFormResp = facePlatFormFuture.get(6000, TimeUnit.MILLISECONDS); Callable<Response<FaceInfoResult>> faceInfoCallable = () -> faceJsfService.getFaceInfo(faceInfoParam);
Future<Response<FaceInfoResult>> faceInfoFuture = faceInfoForkJoinPool.submit(faceInfoCallable);
Response<FaceInfoResult> faceInfoResp = faceInfoFuture.get(6000, TimeUnit.MILLISECONDS);
												

Java异步、线程池解决方案的更多相关文章

  1. java异步线程池同时请求多个接口数据

    一.主要使用类 . ExecutorService java线程池类 申明方式:ExecutorService exc = Executors.newFixedThreadPool(requestPa ...

  2. 沉淀再出发:java中线程池解析

    沉淀再出发:java中线程池解析 一.前言 在多线程执行的环境之中,如果线程执行的时间短但是启动的线程又非常多,线程运转的时间基本上浪费在了创建和销毁上面,因此有没有一种方式能够让一个线程执行完自己的 ...

  3. Java进阶——— 线程池的原理分析

    前言 在了解线程池之前,其实首先出现的疑问是:为什么要使用线程池,其次是了解什么是线程池,最后是如何使用线程池,带着疑问去学习. 为什么要使用 前面多线程文章中,需要使用线程就开启一个新线程,简单方便 ...

  4. spring动态线程池(实质还是用了java的线程池)

    <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.sp ...

  5. Spring Boot系列二 Spring @Async异步线程池用法总结

    1. TaskExecutor Spring异步线程池的接口类,其实质是java.util.concurrent.Executor Spring 已经实现的异常线程池: 1. SimpleAsyncT ...

  6. spring boot:使用async异步线程池发送注册邮件(spring boot 2.3.1)

    一,为什么要使用async异步线程池? 1,在生产环境中,有一些需要延时处理的业务场景: 例如:发送电子邮件, 给手机发短信验证码 大数据量的查询统计 远程抓取数据等 这些场景占用时间较长,而用户又没 ...

  7. SpringBoot使用异步线程池实现生产环境批量数据推送

    前言 SpringBoot使用异步线程池: 1.编写线程池配置类,自定义一个线程池: 2.定义一个异步服务: 3.使用@Async注解指向定义的线程池: 这里以我工作中使用过的一个案例来做描述,我所在 ...

  8. 深入理解Java之线程池

    原作者:海子 出处:http://www.cnblogs.com/dolphin0520/ 本文归作者海子和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则 ...

  9. Java中线程池的学习

    线程池的基本思想还是一种对象池的思想,开辟一块内存空间,里面存放了众多(未死亡)的线程,池中线程执行调度由池管理器来处理.当有线程任务时,从池中取一个,执行完成后线程对象归池,这样可以避免反复创建线程 ...

  10. java利用线程池处理集合

    java利用线程池处理集合 2018年07月23日 17:21:19 衍夏成歌 阅读数:866   版权声明:本文为博主原创文章,未经博主允许不得转载. https://blog.csdn.net/s ...

随机推荐

  1. Python学习第十八篇——低耦合函数设计思想

    import json 2 def greet_user(filename): 3 try: 4 with open(filename) as f_obj: 5 username = json.loa ...

  2. Python的socket模块与交互式指令

    socket简介 在编程的过程中,我们需要使用网络编程,这时我们不得不和网络通信的底层基础打交道了.我们必须让自己传输的数据符合网络通信的基本协议,即TCP/IP协议,但是网络通信协议本身很复杂.我们 ...

  3. PS调出唯美冷色情侣婚纱写真照

    一.打开PS原片,原片是一张JPG格式的片子 色温较高整个画面较红离对着上面的我们标准的韩式色调我们来进行调节吧 ,我就不打太多文字解释一些基本常规了 二.韩式婚纱内景喜欢加点烟雾.其实我本人是不太喜 ...

  4. python 3.6.1 安装scrapy踩坑之旅

    系统环境:win10 64位系统安装 python基础环境配置不做过多的介绍 window环境安装scrapy需要依赖pywin32,下载对应python版本的exe文件执行安装,下载的pywin32 ...

  5. React Native之TextInput的介绍与使用(富文本封装与使用实例,常用输入框封装与使用实例)

    React Native之TextInput的介绍与使用(富文本封装与使用实例,常用输入框封装与使用实例) TextInput组件介绍 TextInput是一个允许用户在应用中通过键盘输入文本的基本组 ...

  6. IdentityServer4【Topic】之保护APIs

    Protecting APIs 保护api 默认情况下IdentityServer将access token发布成JWT(json web token)格式的. 现在,每个相关的平台都支持验证JWT令 ...

  7. IDEA 各版本在线激活(激活码)

    lan yu 大佬的授权又被封杀了,还好我收藏了一些其他的服务器地址. 在线授权服务器 https://jetlicense.nss.im/ 授权代码 K03CHKJCFT-eyJsaWNlbnNlS ...

  8. JavaMail入门第一篇 邮件简介及API概述

    现如今,电子邮件在我们的生活当中扮演着越来越重要的角色,我们每个人几乎都会与其打交道(至少时不时我们都会接收到莫名其妙的垃圾邮件),在工作中,使用邮件进行交流沟通,可以使我们的工作有迹可循,也显的较为 ...

  9. C# Note22: 《Effective C#》笔记

    参考:<Effective C#>快速笔记(一)- C# 语言习惯 参考:<Effective C#>快速笔记(二)- .NET 资源托管 参考:<Effective C ...

  10. php-memcached详解

    一.memcached 简介 在很多场合,我们都会听到 memcached 这个名字,但很多同学只是听过,并没有用过或实际了解过,只知道它是一个很不错的东东.这里简单介绍一下,memcached 是高 ...