Java异步、线程池解决方案
一、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异步、线程池解决方案的更多相关文章
- java异步线程池同时请求多个接口数据
一.主要使用类 . ExecutorService java线程池类 申明方式:ExecutorService exc = Executors.newFixedThreadPool(requestPa ...
- 沉淀再出发:java中线程池解析
沉淀再出发:java中线程池解析 一.前言 在多线程执行的环境之中,如果线程执行的时间短但是启动的线程又非常多,线程运转的时间基本上浪费在了创建和销毁上面,因此有没有一种方式能够让一个线程执行完自己的 ...
- Java进阶——— 线程池的原理分析
前言 在了解线程池之前,其实首先出现的疑问是:为什么要使用线程池,其次是了解什么是线程池,最后是如何使用线程池,带着疑问去学习. 为什么要使用 前面多线程文章中,需要使用线程就开启一个新线程,简单方便 ...
- spring动态线程池(实质还是用了java的线程池)
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.sp ...
- Spring Boot系列二 Spring @Async异步线程池用法总结
1. TaskExecutor Spring异步线程池的接口类,其实质是java.util.concurrent.Executor Spring 已经实现的异常线程池: 1. SimpleAsyncT ...
- spring boot:使用async异步线程池发送注册邮件(spring boot 2.3.1)
一,为什么要使用async异步线程池? 1,在生产环境中,有一些需要延时处理的业务场景: 例如:发送电子邮件, 给手机发短信验证码 大数据量的查询统计 远程抓取数据等 这些场景占用时间较长,而用户又没 ...
- SpringBoot使用异步线程池实现生产环境批量数据推送
前言 SpringBoot使用异步线程池: 1.编写线程池配置类,自定义一个线程池: 2.定义一个异步服务: 3.使用@Async注解指向定义的线程池: 这里以我工作中使用过的一个案例来做描述,我所在 ...
- 深入理解Java之线程池
原作者:海子 出处:http://www.cnblogs.com/dolphin0520/ 本文归作者海子和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则 ...
- Java中线程池的学习
线程池的基本思想还是一种对象池的思想,开辟一块内存空间,里面存放了众多(未死亡)的线程,池中线程执行调度由池管理器来处理.当有线程任务时,从池中取一个,执行完成后线程对象归池,这样可以避免反复创建线程 ...
- java利用线程池处理集合
java利用线程池处理集合 2018年07月23日 17:21:19 衍夏成歌 阅读数:866 版权声明:本文为博主原创文章,未经博主允许不得转载. https://blog.csdn.net/s ...
随机推荐
- LeetCode 832. Flipping an Image
Given a binary matrix A, we want to flip the image horizontally, then invert it, and return the resu ...
- Flask的蓝图和红图
1.蓝图 对于简单的项目来说,比如项目就只有一个user模块,我们可以都将视图函数定义在一个文件里面,不需要用到蓝图. 但是如果我们的项目有多个模块,如下有v1模块,v2模块.....等,那么如果我们 ...
- 计算机名称改名之后,tfs连接问题
计算机名称改名之后,我们发现tfs连接会有问题 打开vs下的“开发人员命令提示”执行下面两条语句: 1.tf workspaces 2.tf workspaces /collection:http:/ ...
- HDU - 1166 - 敌兵布阵 线段树的单点修改,区间求和
#include<iostream> #include<stdio.h> #include<string.h> #include<algorithm> ...
- codeforces#552 D. Vanya and Triangles(几何)
题意:给出n个不同的点,问能组成多少个不同的三角形 题解:对于每个点对,我们生成一个直线,用a*x+b=y表示,用map记录ab,这样就确定了一个直线,这样我们就能算出有多少点是共线的,这样复杂度就是 ...
- E. Superhero Battle
链接 [https://codeforces.com/contest/1141/problem/E] 题意 怪物开始的生命值,然后第i分钟生命值的变化 问什么时候怪物生命值为非正 分析 有一个巨大的坑 ...
- c++入门之字符相关入门
先上代码: # include "iostream" # include "string" //# define BYTE char//注意,这里没有分号,且# ...
- 计算Java List中的重复项出现次数
import java.util.ArrayList;import java.util.HashMap;import java.util.Iterator;import java.util.List; ...
- Windows之PowerShell使用命令
Windows之PowerShell使用命令 切换 命令格式: cd [option] 切换到上一级目录 cd ../ 或者 cd .. 不同磁盘之间切换 盘符: 清屏 清空当前窗口的内容 cls 查 ...
- 最全的Django入门及常用配置
Django 常用配置 Django 安装 pipx install django x 为python解释器版本2 or 3 如果你想安装指定版本的django,使用pip install djang ...