java并行之parallelStream与CompletableFuture比较
1.
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit; import static java.util.stream.Collectors.joining;
import static java.util.stream.Collectors.toList; public class CompletableFutureTest {
static final UserFeatureable[] UserFeatures = {new GetCareerUserFeature(), new GetTradeUserFeature(), new
GetVipLevelUserFeature()}; public static void main(String[] args) {
int id = 10001;
List<UserFeatureable> userFeatures = Arrays.asList(UserFeatures);
long startTime = System.currentTimeMillis();
String result = userFeatures.parallelStream().map(p -> p.getKey() + ":" + p.getValue(id)).collect(joining(","));
long endTime = System.currentTimeMillis();
System.out.println(String.format("parallelStream消耗时间:%d,返回结果:%s", (endTime - startTime), result)); startTime = System.currentTimeMillis();
List<Future<String>> futureList = userFeatures.stream().map(
p -> CompletableFuture.supplyAsync(() -> p.getKey() + ":" + p.getValue(id)))
.collect(toList());
result = futureList.stream().map(p->getVal(p,"")).collect(joining(","));
endTime = System.currentTimeMillis();
System.out.println(String.format("CompletableFuture的默认的ForkJoin线程池消耗时间:%d,返回结果:%s", (endTime - startTime),
result)); //当userFeature越多,使用自定义线程池更有利
startTime = System.currentTimeMillis();
futureList = userFeatures.stream().map(
p -> CompletableFuture.supplyAsync(() -> p.getKey() + ":" + p.getValue(id),CustomThreadPool.INSTANCE))
.collect(toList());
result = futureList.stream().map(p->getVal(p,"")).collect(joining(","));
endTime = System.currentTimeMillis();
System.out.println(String.format("CompletableFuture的自定义线程池消耗时间:%d,返回结果:%s", (endTime - startTime), result));
} private static <T>T getVal(Future<T> future,T defaultV){
try {
return future.get(2,TimeUnit.SECONDS);
}catch (Exception ex){
return defaultV;
}
}
} interface UserFeatureable {
String getKey(); String getValue(int id);
} class GetCareerUserFeature implements UserFeatureable { @Override
public String getKey() {
return "career";
} @Override
public String getValue(int id) {
try {
Thread.sleep(1000);
} catch (InterruptedException ex) { }
return "10";
}
} class GetTradeUserFeature implements UserFeatureable { @Override
public String getKey() {
return "trade";
} @Override
public String getValue(int id) {
try {
Thread.sleep(1000);
} catch (InterruptedException ex) { }
return "5";
}
} class GetVipLevelUserFeature implements UserFeatureable { @Override
public String getKey() {
return "vip";
} @Override
public String getValue(int id) {
try {
Thread.sleep(1000);
} catch (InterruptedException ex) { }
return "v1";
}
}
2.自定义线程池配置
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit; public class CustomThreadPool {
/**
* 默认核心线程池大小
*/
private static final int DEFAULT_CORE_POOL_SIZE = Runtime.getRuntime().availableProcessors(); /**
* 最大线程池大小
* 最佳线程数目 = (线程等待时间与线程CPU时间之比 + 1)* CPU数目
* 最佳线程数目 = (1s/0.1s + 1) * CPU数目
*/
private static final int DEFAULT_MAXIMUM_POOL_SIZE = 11 * DEFAULT_CORE_POOL_SIZE; /**
* 超过核心线程后,空闲线程等待时间
*/
private static final long DEFAULT_KEEP_ALIVE_SECONDS = 10; /**
* 等待执行的线程队列
*/
private static BlockingQueue<Runnable> WORK_QUEUE = new LinkedBlockingDeque(DEFAULT_MAXIMUM_POOL_SIZE * 2); public static ThreadPoolExecutor INSTANCE = new ThreadPoolExecutor(
DEFAULT_CORE_POOL_SIZE,
DEFAULT_MAXIMUM_POOL_SIZE,
DEFAULT_KEEP_ALIVE_SECONDS,
TimeUnit.SECONDS,
WORK_QUEUE,
new ThreadFactoryBuilder().setNameFormat("task-pool-thread-%d").build()); }
3.结果
parallelStream消耗时间:2889,返回结果:career:10,trade:5,vip:v1
CompletableFuture的ForkJoin线程池消耗时间:1010,返回结果:career:10,trade:5,vip:v1
CompletableFuture的自定义线程池消耗时间:1011,返回结果:career:10,trade:5,vip:v1
java并行之parallelStream与CompletableFuture比较的更多相关文章
- Java 并行与并发
Java 并行与并发 注意两个词:并行(Concurrent) 并发(Parallel) 并行:是逻辑上同时发生,指在某一个时间内同时运行多个程序 并发:是物理上同时发生,指在某一个时间点同时运行多个 ...
- Java并发程序设计(二)Java并行程序基础
Java并行程序基础 一.线程的生命周期 其中blocked和waiting的区别: 作者:赵老师链接:https://www.zhihu.com/question/27654579/answer/1 ...
- JAVA并行程序基础
JAVA并行程序基础 一.有关线程你必须知道的事 进程与线程 在等待面向线程设计的计算机结构中,进程是线程的容器.我们都知道,程序是对于指令.数据及其组织形式的描述,而进程是程序的实体. 线程是轻量级 ...
- 避坑 | Java8使用并行流(ParallelStream)注意事项
示例分析 /** * 避坑 | Java8使用并行流(ParallelStream)注意事项 * * @author WH.L * @date 2020/12/26 17:14 */ public c ...
- JAVA并行程序基础二
JAVA并行程序基础二 线程组 当一个系统中,如果线程较多并且功能分配比较明确,可以将相同功能的线程放入同一个线程组里. activeCount()可获得活动线程的总数,由于线程是动态的只能获取一个估 ...
- JAVA并行程序基础一
JAVA并行程序基础一 线程的状态 初始线程:线程的基本操作 1. 新建线程 新建线程只需要使用new关键字创建一个线程对象,并且用start() ,线程start()之后会执行run()方法 不要直 ...
- Java8使用并行流(ParallelStream)注意事项
Java8并行流ParallelStream和Stream的区别就是支持并行执行,提高程序运行效率.但是如果使用不当可能会发生线程安全的问题.Demo如下: public static void co ...
- JAVA使用并行流(ParallelStream)时要注意的一些问题
https://blog.csdn.net/xuxiaoyinliu/article/details/73040808
- Java:并行编程及同步使用方法
知道java可以使用java.util.concurrent包下的 CountDownLatch ExecutorService Future Callable 实现并行编程,并在并行线程同步时,用起 ...
随机推荐
- 全球顶尖大学的UX课程资源,英文!
本文由MOCKPLUS团队原创,转载请标明出处,原型设计工具就用更快.更简单的mockplus 要想成为一名优秀的UX设计师,需要掌握很多必备技能.比如,掌握用户体验设计的所有知识和信息架构(易用性方 ...
- android listView布局等分列
android listView布局4等分列. 必须要加上<RelativeLayout 在外层,不然等分不起作用 <RelativeLayout xmlns:android=" ...
- java类的泛型DAO
@Transactional public abstract class DAOSupport<T> implements DAO<T> { protected Class&l ...
- RedHat6使用centos6的yum源
更换源 cd /etc/yum.repos.d/ wget http://mirrors.163.com/.help/CentOS6-Base-163.repo vi CentOS6-Base-.re ...
- Webservice初级问题: FAILED TO READ WSDL document
这个问题是说明,这个版本的没法下载 犯错的图样 处理方法一: 将网页上xml文档下载,保存在本地,然后错误提示的这几行删除,保存文档,然后从本地调用 (1)右键另存为 保存为文件名a.xml (2)打 ...
- mongodb-win32-i386-3.0.6 使用
一.下载地址 https://fastdl.mongodb.org/win32/mongodb-win32-i386-3.0.6.zip 二.安装 1. systeminfo OS 名称: Micro ...
- C++笔记16之const的用法总结
const主要是为了程序的健壮型,减少程序出错. 最基本的用法: const int a=100; b的内容不变,b只能是100也就是声明一个int类型的常量(#define b =100) int ...
- WIN7或2008远程连接特别慢的解决方法 【转】
方法一. 原因在于从vista开始,微软在TCP/IP协议栈里新加了一个叫做“Window Auto-Tuning”的功能.这个功能本身的目的是为了让操作系统根据网络的实时性能,(比如响应时间)来动态 ...
- 详解CSS盒模型
原文地址:http://luopq.com/2015/10/26/CSS-Box-Model/ 本文主要是学习CSS盒模型的笔记,总结了一些基本概念,知识点和细节. 一些基本概念 HTML的大多数元素 ...
- Sql里时间加减
简单的时间加减 DATEADD(dd,-30, GETDATE())) 使用DateADD方法: 参数1:间隔,表示要添加的时间间隔,一天还是一月还是一年 参数2:要加或减的个数,加一年或加一月 参数 ...