首页 > 其他分享 >【JUC】8-CompletableFutrue的常用方法

【JUC】8-CompletableFutrue的常用方法

时间:2024-06-15 09:54:52浏览次数:12  
标签:JUC 常用 return System result CompletableFutrue println public out

1、获得结果和触发计算

获得结果

1 public T get()
2 
3 public T get(long timeOut, Timeunit unit)
4 
5 public T join()
6 
7 public getNow(T valueIfAbsent)

主动触发计算

public boolean complete(T value)

 

2、对计算结果进行处理

计算结果存在依赖关系,这两个线程串行化

1 thenApply()
计算结果存在依赖关系,这两个线程串行化,步骤有异常也可以往下走,根据带的异常参数可以进一步往下走
1 handle()

 

示例代码

  1 package com.heima.Thread;
  2 
  3 import java.util.concurrent.*;
  4 
  5 public class CompletableFutureApiDemo {
  6     private static final ExecutorService THREAD_POOL = Executors.newFixedThreadPool(3);
  7 
  8     public static void main(String[] args) {
  9         try {
 10             // public T getNow(T valueIfAbsent)
 11             test_getNow();
 12             // public boolean complete(T value)  是否打断get()方法立即返回括号值
 13             test_complete();
 14             // thenApply() 计算结果存在依赖关系,这两个线程串行化
 15             test_thenApply();
 16             // handle() 计算结果存在依赖关系,这两个线程串行化,步骤有异常也可以往下走,根据带的异常参数可以进一步往下走
 17             test_handle();
 18         } finally {
 19             THREAD_POOL.shutdown();
 20         }
 21     }
 22 
 23     private static void test_handle() {
 24         CompletableFuture.supplyAsync(() -> {
 25             try {
 26                 TimeUnit.SECONDS.sleep(1);
 27             } catch (Exception e) {
 28                 e.printStackTrace();
 29             }
 30             System.out.println("step 1");
 31             return ThreadLocalRandom.current().nextInt();
 32         }, THREAD_POOL).handle((f, e) -> {
 33             int i = 10/0;
 34             System.out.println("step 2, get result " + f);
 35             return f + 2;
 36         }).handle((f, e) -> {
 37             System.out.println("step 3, get result " + f);
 38             return f * 3;
 39         }).whenComplete((v, e) -> {
 40             if (e == null) {
 41                 System.out.println("result is " + v);
 42             }
 43         }).exceptionally(e -> {
 44             e.printStackTrace();
 45             System.out.println(e.getMessage());
 46             return null;
 47         });
 48 
 49 
 50         // CompletableFuture使用默认的ForkJoinPool时,主线程结束时,其他线程也会结束
 51         System.out.println("Thread " + Thread.currentThread().getName() + " process other task.");
 52     }
 53 
 54     private static void test_thenApply() {
 55         CompletableFuture.supplyAsync(() -> {
 56             try {
 57                 TimeUnit.SECONDS.sleep(1);
 58             } catch (Exception e) {
 59                 e.printStackTrace();
 60             }
 61             System.out.println("step 1");
 62             return ThreadLocalRandom.current().nextInt();
 63         }, THREAD_POOL).thenApply(f -> {
 64             System.out.println("step 2, get result " + f);
 65             return f + 2;
 66         }).thenApply(f -> {
 67             System.out.println("step 3, get result " + f);
 68             return f * 3;
 69         }).whenComplete((v, e) -> {
 70             if (e == null) {
 71                 System.out.println("result is " + v);
 72             }
 73         }).exceptionally(e -> {
 74             e.printStackTrace();
 75             System.out.println(e.getMessage());
 76             return null;
 77         });
 78 
 79 
 80         // CompletableFuture使用默认的ForkJoinPool时,主线程结束时,其他线程也会结束
 81         System.out.println("Thread " + Thread.currentThread().getName() + " process other task.");
 82     }
 83 
 84 
 85     private static void test_getNow() {
 86 
 87         CompletableFuture<String> result = CompletableFuture.supplyAsync(() -> {
 88             try {
 89                 TimeUnit.SECONDS.sleep(2);
 90             } catch (Exception e) {
 91                 e.printStackTrace();
 92             }
 93             return "ok";
 94         }, THREAD_POOL);
 95 
 96         System.out.println(result.getNow("not ok"));
 97 
 98     }
 99 
100     private static void test_complete() {
101         CompletableFuture<String> result = CompletableFuture.supplyAsync(() -> {
102             try {
103                 TimeUnit.SECONDS.sleep(2);
104             } catch (Exception e) {
105                 e.printStackTrace();
106             }
107             return "ok";
108         }, THREAD_POOL);
109 
110         try {
111             TimeUnit.SECONDS.sleep(1);
112         } catch (Exception e) {
113             e.printStackTrace();
114         }
115         System.out.println(result.complete("completable ok") + "\t" + result. Join());
116     }
117 }

 

3、对计算结果进行消费

 

4、对计算速度进行选用

 

5、对计算结果进行合并

标签:JUC,常用,return,System,result,CompletableFutrue,println,public,out
From: https://www.cnblogs.com/zhaohan258/p/18249015

相关文章

  • 【mongoDB】常用操作命令
    一、官网https://www.mongodb.com/zh-cn/docs/mongodb-shell/crud/ 二、简单介绍1、基本概念 2、数据类型 三、常用shell操作1、数据库操作//查看当前服务器上的数据库showdbs;showdatabases;//选择名为mydb的数据库(如果没有则创建)usemydb;//查看当前......
  • Java最全知识脑图 涵盖 juc mysql git mybatis 等 面试必备
    Java初中级知识脑图面试超实用1.Git下载链接导图下载地址:https://mm.edrawsoft.cn/mobile-share/index.html?uuid=31d00742157057-src&share_type=12.JUC下载链接https://mm.edrawsoft.cn/mobile-share/index.html?uuid=6c0be457444921-src&share_type=13.JVM下载链......
  • freeswitch 常用命令
    mod_callcenter模块:callcenter_configagentadd[name][type]callcenter_configagentdel[name]callcenter_configagentreload[name]callcenter_configagentsetstatus[agent_name][status]callcenter_configagentsetstate[agent_name][state]callcenter......
  • 常用的虚拟化技术比较
    基于Linux的虚拟化技术Xen:内核虚拟化,支持高度隔离和安全性,但已经逐渐过时。KVM(Kernel-basedVirtualMachine):内核虚拟化,提供高安全性和隔离性,性能较好且广受欢迎。OpenVZ:平台虚拟化,基于容器的技术,只支持Linux,安全性较好,但逐渐过时。Docker:容器虚拟化,只支持Linux,提供轻量级......
  • git push 常用操作
    gitpush是Git中用于将本地分支的更改推送到远程仓库的命令。在此处记录一下,方便日后遗忘后查找。以下是gitpush的一些常用操作及其解释:1.推送当前分支到远程同名分支gitpushorigin这个命令会将当前分支的最新提交推送到origin这个远程仓库中对应的同名分支。如......
  • git操作常用命令总结
    要将本地代码同步到公司仓库,您需要遵循以下步骤:安装Git:如果您还没有安装Git,请访问Git官网(https://git-scm.com/)下载并安装适合您操作系统的版本。初始化Git仓库:在本地计算机上,导航到您要克隆公司仓库的目录,然后运行以下命令:gitinit这将初始化一个Git仓库,但请注意,......
  • linux常用命令.md
    学习了一段时间的linux之后,开始着手基本命令的学习,这里主要记录一些学习过程中重要的知识点供以后查阅。1、系统资源监控命令1)文件系统查看命令dfdf命令是从文件系统考虑的,不光要考虑文件占用的空间,还要统计被命令和程序占用的空间(最常见的是文件已经被删除,但是程序并没有释放......
  • poi - 常用单元格样式
    这是4.1.2版本的写法,poi版本差异较大,按需调整。importorg.apache.poi.ss.usermodel.*;/***Excel常用样式参考*<p>*很复杂的样式,可以使用Excel模版,从现有的Excel中直接读取样式,*平时很少写这些样式,留作参考。**@authorMr.css*@version2023-09-15......
  • Nginx常用命令
    以下是一些常见的NGINX交互命令及其作用:nginx-sreload:重新加载NGINX配置文件,使新的配置生效,而不需要重启NGINX服务器。nginx-sstop:优雅地停止NGINX服务器,允许当前连接完成后再停止服务。nginx-squit:优雅地停止NGINX服务器,并等待所有连接完成后再停止服务。nginx......
  • 【Git系列】Git LFS常用命令的使用
    前言LFS是LargeFileStorage的缩写,是一个Git扩展,用于管理大型二进制文件,它允许将这些文件存储在单独的存储库中,以便更有效地处理Git仓库。常用命令LFS安装gitlfs要求git>=1.8.2linux环境:gitlfsinstall执行显示UpdatedGithooks.GitLFSinitialized.......