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的更多相关文章

  1. Java 多线程异步处理demo

    java中实现多线程 1)继承Thread,重写里面的run方法 2)实现runnable接口通过源码发现:第一种方法说是继承Tread然后重写run方法,通过查看run方法的源码,发现run方法里面 ...

  2. WinForm多线程编程简单Demo

    需要搭建一个可以监控报告生成的CS(WinForm)工具,即CS不断Run,执行获取数据生成报告,经过研究和实践,选择了使用"WinForm多线程编程"的解决方案.当然参考了园中相 ...

  3. (转)浅谈.NET下的多线程和并行计算(一)前言

    转载——原文地址:http://www.cnblogs.com/lovecindywang/archive/2009/12/25/1632014.html 作为一个ASP.NET开发人员,在之前的开发 ...

  4. 使用libevent进行多线程socket编程demo

    最近要对一个用libevent写的C/C++项目进行修改,要改成多线程的,故做了一些学习和研究. libevent是一个用C语言写的开源的一个库.它对socket编程里的epoll/select等功能 ...

  5. java多线程的简单demo

    模拟场景:顾客买车从车库中取车,厂家生产车,车存储在车库中.买家.厂家对同一个车库中的车操作 一.不加同步机制的代码如下: package com.joysuch.testng.thread; imp ...

  6. java8 - 多线程时间安全问题

    import java.text.SimpleDateFormat; import java.time.LocalDate; import java.time.format.DateTimeForma ...

  7. iOS多线程 iOS开发Demo(示例程序)源代码

    本系列所有开发文档翻译链接地址:iOS7开发-Apple苹果iPhone开发Xcode官方文档翻译PDF下载地址(2013年12月29日更新版)   iOS程序源代码下载链接:01.大任务.zip22 ...

  8. java创建多线程实现并行计算任务处理

    1.直接上代码一看明白: package multithreadingTest; class fblib extends Thread{ public static Integer fb(Intege ...

  9. java多线程并发执行demo,主线程阻塞

    其中有四个知识点我单独罗列了出来,属于多线程编程中需要知道的知识: 知识点1:X,T为泛型,为什么要用泛型,泛型和Object的区别请看:https://www.cnblogs.com/xiaoxio ...

  10. java 多线程断点下载demo

    源码链接 import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java ...

随机推荐

  1. Java编程技巧之样板代码

    简介: 在日常编码的过程中,可以总结出很多"样板代码",就像"活字印刷术中的"活字"一样.当我们编写新的代码时,需要用到这些"活字" ...

  2. 慢SQL治理分享

    简介: 这里的慢SQL指的是MySQL慢查询,是运行时间超过long_query_time值的SQL.真实的慢SQL通常会伴随着大量的行扫描.临时文件排序或者频繁的磁盘flush,直接影响就是磁盘IO ...

  3. 从原始边列表到邻接矩阵Python实现图数据处理的完整指南

    本文分享自华为云社区<从原始边列表到邻接矩阵Python实现图数据处理的完整指南>,作者: 柠檬味拥抱. 在图论和网络分析中,图是一种非常重要的数据结构,它由节点(或顶点)和连接这些节点的 ...

  4. Ubuntu-kali配置动态ip(简单)

    使用gedit文本编辑器打开网络接口配置文件 gedit /etc/network/interfaces 新增两行内容如下: auto eth0 iface eth0 inet dhcp 其意思为:网 ...

  5. SQL中常用的字符串CHARINDEX函数和PATINDEX函数详解!

    今天整理了些日常可能经常遇到的一些处理字符串的函数,有些可能在写SQL时突然间想不到如何使用,今天就给大家总结两个函数的应用方法,以备不时之需!记得点赞收藏! CHARINDEX(expression ...

  6. C 语言编程 — 运算符

    目录 文章目录 目录 前文列表 运算符 算数运算符 自增.自减运算符 比较运算符 逻辑运算符 位运算符 赋值运算符 逗号运算符 sizeof 运算符 杂项运算符 运算符的优先级 前文列表 <程序 ...

  7. sql 常用手册

    根据code 分组然后取出每组中的任意一行 SELECT *from( SELECT *, row_number () OVER ( partition BY code ORDER BY code D ...

  8. PVT:特征金字塔在Vision Transormer的首次应用,又快又好 | ICCV 2021

    论文设计了用于密集预测任务的纯Transformer主干网络PVT,包含渐进收缩的特征金字塔结构和spatial-reduction attention层,能够在有限的计算资源和内存资源下获得高分辨率 ...

  9. SASS 插值语句 #{ }的使用

    在之前我们已经使用用 / 来进行计算,但如下情况不一样 例如 p{ font: 16px/30px Arial, Helvetica, sans-serif; } 如果需要使用变量,同时又要确保 / ...

  10. Android 12(S) MultiMedia Learning(九)MediaCodec

    这一节来学习MediaCodec的工作原理,相关代码路径: http://aospxref.com/android-12.0.0_r3/xref/frameworks/av/media/libstag ...