首页 > 编程语言 >Java8 高级功能CompletableFuture

Java8 高级功能CompletableFuture

时间:2023-08-06 16:02:40浏览次数:32  
标签:return Thread System 高级 CompletableFuture println Java8 out

CompletableFuture功能测试

CompletableFuture类实现了CompletionStage和Future接口。Future是Java 5添加的类,用来描述一个异步计算的结果,但是获取一个结果时方法较少,要么通过轮询isDone,确认完成后,调用get()获取值,要么调用get()设置一个超时时间。但是这个get()方法会阻塞住调用线程,这种阻塞的方式显然和我们的异步编程的初衷相违背。 为了解决这个问题,JDK吸收了guava的设计思想,加入了Future的诸多扩展功能形成了CompletableFuture。 CompletionStage是一个接口,从命名上看得知是一个完成的阶段,它里面的方法也标明是在某个运行阶段得到了结果之后要做的事情。

package java8test.Java8Future;

import java.util.concurrent.CompletableFuture;

/**
 * 描述:
 * Created 002267 by on 2017-10-18 21:00:54
 */
public class CompletableFutureTest {

	public static void main(String[] args) {

		CompletableFutureTest test = new CompletableFutureTest();
		//        test.thenApply();

		//future callback

		//        test.thenAccept();

		//        test.thenRun();

		test.thenCombine();
	}

	//它的入参是上一个阶段计算后的结果,返回值是经过转化后结果
	public void thenApply() {
		String result = CompletableFuture.supplyAsync(() -> "hello").thenApply(s -> s + " world").join();
		System.out.println(result);

	}


	//thenAccept是针对结果进行消耗,因为他的入参是Consumer,有入参无返回值。
	public void thenAccept() {
		CompletableFuture.supplyAsync(() -> "hello").thenAccept(s -> System.out.println(s + " world"));
	}

	//对上一步的计算结果不关心,执行下一个操作
	public void thenRun() {
		//        Future<String>
		CompletableFuture.supplyAsync(() -> {
			try {
				Thread.sleep(20 * 1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			return "hello";
		}).thenRun(() -> System.out.println("hello world then run"));
		while (true) {
			try {
				System.out.println("<<<running>>>");
				Thread.sleep(10 * 1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}

	public void aa(){
		asyncFile().whenComplete((val, throwable) ->{
			System.out.println("sdafsadfsdafsdafdsaf");
		});


		System.out.println("query user");

	}
	//  if (!file.isEmpty()) asyncFile(file).whenComplete((val, throwable) -> bannerInfoDto.setBannerUrl(val));a
	private CompletableFuture<String> asyncFile() {
		CompletableFuture<String> futurePrice = new CompletableFuture<>();
		new Thread(() -> {
			System.out.println("12312312");
		}).start();
		return futurePrice;
	}

	//结合两个CompletionStage的结果,进行转化后返回
	public void thenCombine() {
		String result = CompletableFuture.supplyAsync(() -> {
			try {
				Thread.sleep(2000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			return "hello";
		}).thenCombine(CompletableFuture.supplyAsync(() -> {
			try {
				Thread.sleep(3000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			return "world";
		}), (s1, s2) -> s1 + " " + s2).join();
		System.out.println(result);
	}

	//结合两个CompletionStage的结果,进行消耗
	public void thenAcceptBoth() {
		CompletableFuture.supplyAsync(() -> {
			try {
				Thread.sleep(2000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			return "hello";
		}).thenAcceptBoth(CompletableFuture.supplyAsync(() -> {
			try {
				Thread.sleep(3000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			return "world";
		}), (s1, s2) -> System.out.println(s1 + " " + s2));
		while (true) {
		}
	}

	//在两个CompletionStage都运行完执行。

	public void runAfterBoth() {
		CompletableFuture.supplyAsync(() -> {
			try {
				Thread.sleep(2000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			return "s1";
		}).runAfterBothAsync(CompletableFuture.supplyAsync(() -> {
			try {
				Thread.sleep(3000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			return "s2";
		}), () -> System.out.println("hello world"));
		while (true) {
		}
	}

	//两个CompletionStage,谁计算的快,我就用那个CompletionStage的结果进行下一步的转化操作。
	public void applyToEither() {
		String result = CompletableFuture.supplyAsync(() -> {
			try {
				Thread.sleep(3000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			return "s1";
		}).applyToEither(CompletableFuture.supplyAsync(() -> {
			try {
				Thread.sleep(2000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			return "hello world";
		}), s -> s).join();
		System.out.println(result);
	}

	//两个CompletionStage,谁计算的快,我就用那个CompletionStage的结果进行下一步的消耗操作。
	public void acceptEither() {
		CompletableFuture.supplyAsync(() -> {
			try {
				Thread.sleep(3000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			return "s1";
		}).acceptEither(CompletableFuture.supplyAsync(() -> {
			try {
				Thread.sleep(2000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			return "hello world";
		}), System.out::println);
		while (true) {
		}
	}

	//两个CompletionStage,任何一个完成了都会执行下一步的操作(Runnable)
	public void runAfterEither() {
		CompletableFuture.supplyAsync(() -> {
			try {
				Thread.sleep(3000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			return "s1";
		}).runAfterEither(CompletableFuture.supplyAsync(() -> {
			try {
				Thread.sleep(2000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			return "s2";
		}), () -> System.out.println("hello world"));
		while (true) {
		}
	}

	//当运行时出现了异常,可以通过exceptionally进行补偿。
	public void exceptionally() {
		String result = CompletableFuture.supplyAsync(() -> {
			try {
				Thread.sleep(3000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			if (1 == 1) {
				throw new RuntimeException("测试一下异常情况");
			}
			return "s1";
		}).exceptionally(e -> {
			System.out.println(e.getMessage());
			return "hello world";
		}).join();
		System.out.println(result);
	}

	//当运行完成时,对结果的记录。这里的完成时有两种情况,一种是正常执行,返回值。另外一种是遇到异常抛出造成程序的中断。这里为什么要说成记录,因为这几个方法都会返回CompletableFuture,当Action执行完毕后它的结果返回原始的CompletableFuture的计算结果或者返回异常

	public void whenComplete() {
		String result = CompletableFuture.supplyAsync(() -> {
			try {
				Thread.sleep(3000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			if (1 == 1) {
				throw new RuntimeException("测试一下异常情况");
			}
			return "s1";
		}).whenComplete((s, t) -> {
			System.out.println(s);
			System.out.println(t.getMessage());
		}).exceptionally(e -> {
			System.out.println(e.getMessage());
			return "hello world";
		}).join();
		System.out.println(result);
	}

	//行完成时,对结果的处理。这里的完成时有两种情况,一种是正常执行,返回值。另外一种是遇到异常抛出造成程序的中断。
	public void handle() {
		String result = CompletableFuture.supplyAsync(() -> {
			try {
				Thread.sleep(3000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			//出现异常
			if (1 == 1) {
				throw new RuntimeException("测试一下异常情况");
			}
			return "s1";
		}).handle((s, t) -> {
			if (t != null) {
				return "hello world";
			}
			return s;
		}).join();
		System.out.println(result);
	}


}

标签:return,Thread,System,高级,CompletableFuture,println,Java8,out
From: https://blog.51cto.com/u_11906056/6984940

相关文章

  • openGauss学习笔记-32 openGauss 高级数据管理-批处理模式
    openGauss学习笔记-32openGauss高级数据管理-批处理模式openGauss支持从文本文件执行SQL语句。openGauss提供了gsql工具实现SQL语句的批量处理。以下场景建议使用批处理:如果您重复运行查询(例如,每天或每周),将其设为脚本可以让您避免每次进行重复输入。您可以通过复制和编辑脚......
  • 高级 / 资深前端面试题集锦
    以下是一线互联网公司高级前端面试题总结,包括百度、腾讯、网易、字节、知乎、京东、滴滴,小米,感兴趣的欢迎留言交流。1、请简述JsBridge2、请说一下SSR的单机QPS3、请说一下eggJs的初始化原理4、前端错误如何捕获,promise的错误是如何捕获的5、vue的domdiff算法6、vue的Chil......
  • 《软件测试的艺术》原书第三版 - 第六章 - 更高级别的测试
    第六章更高级别的测试软件产品开发周期的模型软件最终用户的要求转换为一系列书面的需求。这些需求就是该软件产品要实现的目标。通过评估可行性与成本、消除相抵触的用户需求、建立优先级和平衡关系,将用户需求转换为具体的目标。将上述目标转换为一个准确的产品规格说明,将......
  • openGauss学习笔记-31 openGauss 高级数据管理-索引
    openGauss学习笔记-31openGauss高级数据管理-索引索引是一个指向表中数据的指针。一个数据库中的索引与一本书的索引目录是非常相似的。索引可以用来提高数据库查询性能,但是不恰当的使用将导致数据库性能下降。建议仅在匹配如下某条原则时创建索引:经常执行查询的字段。在连......
  • openGauss学习笔记-30 openGauss 高级数据管理-别名
    openGauss学习笔记-30openGauss高级数据管理-别名SQL可以重命名一张表或者一个字段的名称,这个名称为该表或该字段的别名。创建别名是为了让表名或列名的可读性更强。SQL中使用AS来创建别名。30.1语法格式30.1.1列别名语法SELECT{*|[column[AS]output_name,...]}......
  • JVM零基础到高级实战之Java内存区域虚拟机栈
    前言JVM零基础到高级实战之Java内存区域虚拟机栈JVM内存模型之虚拟机栈虚拟机栈是什么?用于作用于方法执行的一块Java内存区域为什么要有虚拟机栈?每个方法在执行的同时都会创建一个栈帧(StackFramel)用于存储局部变量表、操作数栈、动态链接、方法出口等信息。每一个方法从调用直至......
  • 高级 - 架构级性能评估与性能调优分析大纲
        做为性能培训的高级部分大纲,将会对各类工具(测试工具、监控工具、分析工具、调试工具)做融会贯通的讲解,并在用实际的示例演示。    另外做为高级部分,也会对建模做深入的讲解,包括系统可用性分析、排队论建模的部分,同时也会用实例说明如何具体实施。从数学基础理论知识到具......
  • openGauss学习笔记-29 openGauss 高级数据管理-UNION子句
    openGauss学习笔记-29openGauss高级数据管理-UNION子句UNION计算多个SELECT语句返回行集合的并集。UNION内部的SELECT语句必须拥有相同数量的列,列也必须拥有相似的数据类型。同时,每条SELECT语句中的列的顺序必须相同。29.1语法格式UNION:结果中如果出现相同的值,仅保留一个。......
  • openGauss学习笔记-28 openGauss 高级数据管理-NULL值
    openGauss学习笔记-28openGauss高级数据管理-NULL值NULL值代表未知数据。无法比较NULL和0,因为它们是不等价的。创建表时,可以指定列可以存放或者不能存放NULL值,详情请参见NOTNULL约束。本节介绍ISNULL和ISNOTNULL操作符。创建表customer_t1,数据如下:openGauss=#SELECT*F......
  • openGauss学习笔记-27 openGauss 高级数据管理- JOIN
    openGauss学习笔记-27openGauss高级数据管理-JOINJOIN子句用于把来自两个或多个表的行结合起来,基于这些表之间的共同字段。在openGauss中,JOIN有五种连接类型:CROSSJOIN:交叉连接INNERJOIN:内连接LEFTOUTERJOIN:左外连接RIGHTOUTERJOIN:右外连接FULLOUTERJOIN:全外连......