一、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. 我的微信小程序第二篇

    在上一篇<我的微信小程序第一篇(入门)>中,很多人问我什么是微信小程序,在这里我要说一下这个是我的失误啦,我默认大家都知道微信小程序,其实可能行内人士都知道小程序,好多非行内朋友可能平时不 ...

  2. SPA单页面优缺点

    优点: 1.体验好,不刷新,减少 请求  数据ajax异步获取 页面流程: 2.前后端分离 3.减轻服务端压力 4.共用一套后端程序代码,设配多端 缺点: 1.首屏加载过慢: 2.SEO 不利于搜索引 ...

  3. poj2226 Muddy Fields 填充棒子(二分匹配)

    参考博客:https://blog.csdn.net/liujc_/article/details/51287019 参考博客:https://blog.csdn.net/acdreamers/art ...

  4. Feel Good POJ - 2796 (前缀和+单调栈)(详解)

    Bill is developing a new mathematical theory for human emotions. His recent investigations are dedic ...

  5. Sagheer and Nubian Market CodeForces - 812C (二分)

    On his trip to Luxor and Aswan, Sagheer went to a Nubian market to buy some souvenirs for his friend ...

  6. 软件扒网站? 爬虫? F12查看源码? 查看网页源代码?浏览器sources? 区别和联系!

    1.软件扒网站: 利用各类扒站网站,如仿站小工具8.0,可以按照规则将网站的未经浏览器简析的前端代码扒下来,并整理成css,js,html等文件夹,很方便.(当然看不到ajax等相关代码) 备注:如果 ...

  7. spring实例入门

    首先是bean文件: package onlyfun.caterpillar; public class HelloBean {    private String helloWord = " ...

  8. C调用C++, C++调用C方法

    1. C 调用 C++封装好后的函数: -> 在C++中有一个函数 int main_cpp(): -> 首先构建头文件, #ifndef CPP_FILE_H   #define CPP ...

  9. [转帖]Huge Page 是否是拯救性能的万能良药?

    Huge Page 是否是拯救性能的万能良药? 本文将分析是否Huge Page在任何条件下(特别是NUMA架构下)都能带来性能提升. 文章欢迎转载,但转载时请保留本段文字,并置于文章的顶部 作者:卢 ...

  10. LLVM的安装

    1. 官网下载 llvm 2. 官网下载cmake 3. configure 执行 llvm 发现报错 4. 解压缩 cmake 5.将cmake 下面的bin 目录放到环境变量里面去 6. 创建一个 ...