Java8 多线程及并行计算demo
Java8 多线程及并行计算demo
#接口
public interface RemoteLoader {
String load(); default void delay() {
try {
Thread.sleep(1000L);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
} #实现类
public class CustomerInfoService implements RemoteLoader{ @Override
public String load() {
this.delay();
return "基本信息";
}
} public class LabelService implements RemoteLoader{ @Override
public String load() {
this.delay();
return "学习标签";
}
} public class LearnRecordService implements RemoteLoader{ @Override
public String load() {
this.delay();
return "学习信息";
}
} public class WatchRecordService implements RemoteLoader{ @Override
public String load() {
this.delay();
return "观看服务";
}
} #测试类
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.*;
import java.util.stream.Collectors; /**
* 参考:https://blog.csdn.net/Alecor/article/details/113405297
*/
public class TestSync {
public static void main(String[] args) throws ExecutionException, InterruptedException { // sync();
// testFuture();
// testParallelStream(); // testCompletableFuture();
// testCompletableFuture2();
// testCompletableFuture3();
testCompletableFuture4();
} /**
* [基本信息, 学习信息]
* 总共花费时间:2036
*/
public static void sync(){
long start = System.currentTimeMillis();
List<RemoteLoader> remoteLoaderList = Arrays.asList(new CustomerInfoService(),new LearnRecordService());
List<String> customerDetail = remoteLoaderList.stream().map(RemoteLoader::load).collect(Collectors.toList());
System.out.println(customerDetail);
long end = System.currentTimeMillis();
System.out.println("总共花费时间:" + (end - start));
} /**
* [基本信息, 学习信息]
* 总共花费时间:1037
*/
public static void testFuture() {
long start = System.currentTimeMillis();
ExecutorService executorService = Executors.newFixedThreadPool(2); List<RemoteLoader> remoteLoaders = Arrays.asList(new CustomerInfoService(), new LearnRecordService()); List<Future<String>> futures = remoteLoaders.stream()
.map(remoteLoader -> executorService.submit(remoteLoader::load))
.collect(Collectors.toList()); List<String> customerDetail = futures.stream()
.map(future -> {
try {
return future.get();
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
return null;
})
.filter(Objects::nonNull)
.collect(Collectors.toList());
System.out.println(customerDetail);
long end = System.currentTimeMillis();
System.out.println("总共花费时间:" + (end - start));
} /**
* [基本信息, 学习信息, 学习标签, 观看服务]
* 总共花费时间:1081
*/
public static void testParallelStream() {
long start = System.currentTimeMillis();
List<RemoteLoader> remoteLoaders = Arrays.asList( new CustomerInfoService(),
new LearnRecordService(),
new LabelService(),
new WatchRecordService());
List<String> customerDetail = remoteLoaders.parallelStream().map(RemoteLoader::load).collect(Collectors.toList());
System.out.println(customerDetail);
long end = System.currentTimeMillis();
System.out.println("总共花费时间:" + (end - start));
} /**
* doSomething...
* Finish
*/
public static void testCompletableFuture() {
CompletableFuture<String> future = new CompletableFuture<>();
new Thread(() -> {
try {
doSomething();
future.complete("Finish");
} catch (Exception e) {
future.completeExceptionally(e);
} //任务执行完成后 设置返回的结果
}).start();
System.out.println(future.join()); //获取任务线程返回的结果
} private static void doSomething() {
System.out.println("doSomething...");
} /**
* doSomething...
* Finish
*
* @throws ExecutionException
* @throws InterruptedException
*/
public static void testCompletableFuture2() throws ExecutionException, InterruptedException {
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
doSomething();
return "Finish";
});
System.out.println(future.get());
} /**
* [基本信息, 学习信息, 学习标签, 观看服务]
* 总共花费时间:1079
*
* @throws ExecutionException
* @throws InterruptedException
*/
public static void testCompletableFuture3() throws ExecutionException, InterruptedException {
long start = System.currentTimeMillis();
List<RemoteLoader> remoteLoaders = Arrays.asList(
new CustomerInfoService(),
new LearnRecordService(),
new LabelService(),
new WatchRecordService());
List<CompletableFuture<String>> completableFutures = remoteLoaders
.stream()
.map(loader -> CompletableFuture.supplyAsync(loader::load).exceptionally(throwable -> "Throwable exception message:" + throwable.getMessage()))
.collect(Collectors.toList()); List<String> customerDetail = completableFutures
.stream()
.map(CompletableFuture::join)
.collect(Collectors.toList()); System.out.println(customerDetail);
long end = System.currentTimeMillis();
System.out.println("总共花费时间:" + (end - start));
} /**
* [基本信息, 学习信息, 学习标签, 观看服务]
* 总共花费时间:1051
*
* @throws ExecutionException
* @throws InterruptedException
*/
public static void testCompletableFuture4() throws ExecutionException, InterruptedException {
long start = System.currentTimeMillis();
List<RemoteLoader> remoteLoaders = Arrays.asList(
new CustomerInfoService(),
new LearnRecordService(),
new LabelService(),
new WatchRecordService()); ExecutorService executorService = Executors.newFixedThreadPool(Math.min(remoteLoaders.size(), 50)); List<CompletableFuture<String>> completableFutures = remoteLoaders
.stream()
.map(loader -> CompletableFuture.supplyAsync(loader::load, executorService))
.collect(Collectors.toList()); List<String> customerDetail = completableFutures
.stream()
.map(CompletableFuture::join)
.collect(Collectors.toList()); System.out.println(customerDetail);
long end = System.currentTimeMillis();
System.out.println("总共花费时间:" + (end - start));
}
}
Java8 多线程及并行计算demo的更多相关文章
- Java 多线程异步处理demo
java中实现多线程 1)继承Thread,重写里面的run方法 2)实现runnable接口通过源码发现:第一种方法说是继承Tread然后重写run方法,通过查看run方法的源码,发现run方法里面 ...
- WinForm多线程编程简单Demo
需要搭建一个可以监控报告生成的CS(WinForm)工具,即CS不断Run,执行获取数据生成报告,经过研究和实践,选择了使用"WinForm多线程编程"的解决方案.当然参考了园中相 ...
- (转)浅谈.NET下的多线程和并行计算(一)前言
转载——原文地址:http://www.cnblogs.com/lovecindywang/archive/2009/12/25/1632014.html 作为一个ASP.NET开发人员,在之前的开发 ...
- 使用libevent进行多线程socket编程demo
最近要对一个用libevent写的C/C++项目进行修改,要改成多线程的,故做了一些学习和研究. libevent是一个用C语言写的开源的一个库.它对socket编程里的epoll/select等功能 ...
- java多线程的简单demo
模拟场景:顾客买车从车库中取车,厂家生产车,车存储在车库中.买家.厂家对同一个车库中的车操作 一.不加同步机制的代码如下: package com.joysuch.testng.thread; imp ...
- java8 - 多线程时间安全问题
import java.text.SimpleDateFormat; import java.time.LocalDate; import java.time.format.DateTimeForma ...
- iOS多线程
iOS开发Demo(示例程序)源代码
本系列所有开发文档翻译链接地址:iOS7开发-Apple苹果iPhone开发Xcode官方文档翻译PDF下载地址(2013年12月29日更新版) iOS程序源代码下载链接:01.大任务.zip22 ...
- java创建多线程实现并行计算任务处理
1.直接上代码一看明白: package multithreadingTest; class fblib extends Thread{ public static Integer fb(Intege ...
- java多线程并发执行demo,主线程阻塞
其中有四个知识点我单独罗列了出来,属于多线程编程中需要知道的知识: 知识点1:X,T为泛型,为什么要用泛型,泛型和Object的区别请看:https://www.cnblogs.com/xiaoxio ...
- java 多线程断点下载demo
源码链接 import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java ...
随机推荐
- MaxCompute中如何通过logview诊断慢作业
建模服务,在MaxCompute执行sql任务的时候有时候作业会很慢,本文通过查看logview排查具体任务慢的原因 在这里把任务跑的慢的问题划分为以下几类 资源不足导致的排队(一般是包年包月项目) ...
- [FAQ] 为什么部署到 github pages 时自定义域名总失效 (push-dir)
Github_Pages 能方便我们部署静态页面,并且还支持 CNAME 自定义域名. $ yarn add --dev push-dir $ xxx build $ push-dir --dir=d ...
- [FAQ] pdf 无法导入 adobe AI, 分辨率 or 颜色缺失 or 字体缺失
属于Adoge软件不支持问题, 可能是分辨率.字体等多种原因. https://www.codebye.com/adobe-reader-or-acrobat-opens-pdf-file-drawi ...
- [Go] 有了 cast 组件, golang 类型转换从此不再困扰
在 golang 中,参数和返回值之间往往涉及 int.string.[].map 等之间的转换. 如果是手动去处理,一容易出错,二不能兼容多数类型,比较麻烦. 使用 cast,能够让代码更健壮.可维 ...
- C# - 自建 SDK 的 API 文档
在代码中添加 API 文档 用户在使用类库时,通常需要通过 VS 的 Intellisense 或 F12 反编译查看 API 的注释,借助这些注释来了解如何使用 API.在 C# 源文件中,可以通过 ...
- LLM优化:开源星火13B显卡及内存占用优化
1. 背景 本qiang~这两天接了一个任务,部署几个开源的模型,并且将本地经过全量微调的模型与开源模型做一个效果对比. 部署的开源模型包括:星火13B,Baichuan2-13B, ChatGLM6 ...
- 🔥 PyTorch神操作:一图秒懂Tensor变形记!
亲爱的码农小伙伴们,你们是否还在为Tensor的各种变换头大如斗?别怕,今天给大家送上一张超实用的PyTorch变换秘籍图,让你的Tensor操作如行云流水,CPU和GPU之间的切换如穿梭自如! GP ...
- VSCode+VUE+ESLint以达到保存自动格式化
首先打开VSCode在.eslintrc.js中加入以下代码(不知道怎么找可以ctrl+shift+p进行搜索),添加 vscode 终端启动服务 // 添加⾃定义规则 'prettier/prett ...
- 集群监管-USDP(智能大数据平台)
UCloud Smart Data Platform(简称 USDP),是 UCloud 推出的智能化.轻量级.适用于私有化部署至客户本地的大数据基础服务平台,通过自研的 USDP Manager 管 ...
- sql 查找是否存在的记录
场景:根据条件从数据库表中查询 『有』与『没有』,只有两种状态 方法1: SELECT count(*) FROM table WHERE a = 1 方法2: SELECT 1 FROM table ...