栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Java8异步编程-CompletableFuture,mysql调优面试题

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Java8异步编程-CompletableFuture,mysql调优面试题

这种实现方法还是不能实现真正的异步编程或者说不是我们所期望的,我们期望的是登录后获取用户信息,但这两件事情完成后统一对结果进行处理,而这种方式是先等待登录之后再取用户信息,和同步调用类似,这就与我们的设想不符。

CompletableFuture 初识CompletableFuture

在Java8中引入了CompletableFuture类,同时实现了Future接口和CompletionStage接口,提供了一套用于异步编程的Api接口并且提供了异步处理

CompletableFuture提供了许多异步编程的操作,可以说是Java中的Promise了,下面通过CompletableFuture来实现上面提到的例子:

String userInfo = CompletableFuture.supplyAsync(() -> login())
.thenApplyAsync(token -> userInfo(token))
.get();

System.out.println(userInfo);

CompletableFuture API

CompletableFuture方法很多,功能也很丰富,这里不一一说明,主要可以分为这几类来使用:

1.把CompletableFuture当Future使用

CompletableFuture实现了Future接口,也就是Future能做的CompletableFuture也同样能使用,加上complete和completeExceptionally方法可以控制结果的结束:

CompletableFuture f = new CompletableFuture<>();

Executors.newSingleThreadExecutor().submit(()->{
f.complete(“hello”);
//f.completeExceptionally(new RuntimeException(“error”));
});

String result = f.get();

System.out.println(result);

可以通过CompletableFuture来控制多个异步操作同时执行:

CompletableFuture f = new CompletableFuture<>();

new Thread(() -> {
try {
System.out.println(“thread1:” + f.get());
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
}).start();

new Thread(() -> {
try {
System.out.println(“thread2:” + f.get());
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
}).start();

f.complete(“hello”);

2.异步操作

创建异步操作的方法主要是:

public static CompletableFuture runAsync(Runnable runnable)
public static CompletableFuture runAsync(Runnable runnable,Executor executor)
public static CompletableFuture supplyAsync(Supplier supplier)
public static CompletableFuture supplyAsync(Supplier supplier,Executor executor)

使用如下:

CompletableFuture f = CompletableFuture.supplyAsync(() -> {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return “hello”;
});

String result = f.get();

System.out.println(result);

3.连续异步操作

public CompletableFuture thenRun(Runnable action)
public CompletableFuture thenRunAsync(Runnable action)
public CompletableFuture thenRunAsync(Runnable action,Executor executor)
public CompletableFuture thenApply(Function fn)
public CompletableFuture thenApplyAsync(Function fn)
public CompletableFuture thenApplyAsync(Function fn, Executor executor)
public CompletableFuture thenAccept(Consumer action)
public CompletableFuture thenAcceptAsync(Consumer action)
public CompletableFuture thenAcceptAsync(Consumer action,Executor executor)

使用如下:

CompletableFuture f = CompletableFuture
.supplyAsync(() -> “hello”)
.thenApplyAsync(res -> res + " world!")
.thenAcceptAsync(System.out::println);
// wait for job done
f.get();

4.等待操作完成

public CompletableFuture whenComplete(BiConsumer

《一线大厂Java面试题解析+后端开发学习笔记+最新架构讲解视频+实战项目源码讲义》

【docs.qq.com/doc/DSmxTbFJ1cmN1R2dB】 完整内容开源分享

uper Throwable> action)
public CompletableFuture whenCompleteAsync(BiConsumer action)
public CompletableFuture whenCompleteAsync(BiConsumer action, Executor executor)

使用如下:

CompletableFuture f = CompletableFuture
.supplyAsync(() -> “hello”)
.thenApplyAsync(res -> res + " world!")
.whenComplete((res, err) -> {
if (err != null) {
err.printStackTrace();
} else {
System.out.println(res);
}
});

// wait for job done
f.get();

5.组合

public CompletableFuture thenCompose(Function> fn)
public CompletableFuture thenComposeAsync(Function> fn)
public CompletableFuture thenComposeAsync(Function> fn,Executor executor)
public CompletableFuture thenCombine(CompletionStage other,BiFunction fn)
public CompletableFuture thenCombineAsync(CompletionStage other,BiFunction fn)
public CompletableFuture thenCombineAsync(CompletionStage other,BiFunction fn, Executor executor)

使用如下:

CompletableFuture f = CompletableFuture.supplyAsync(() -> “Hello”)
.thenCompose(res -> CompletableFuture.supplyAsync(() -> res + " World,"))
.thenCombine(CompletableFuture.supplyAsync(() -> “CompletableFuture!”), (a, b) -> a + b);

String result = f.get();

System.out.println(result);//Hello World,CompletableFuture!

6.结果&异常处理

public CompletableFuture handle(BiFunction fn)
public CompletableFuture handleAsync(BiFunction fn)
public CompletableFuture handleAsync(BiFunction fn, Executor executor)
public CompletableFuture exceptionally(Function fn)

使用如下:

// 异常处理
CompletableFuture f = CompletableFuture.supplyAsync(() -> “Hello”)
.thenApplyAsync(res -> res + “World”)
.thenApplyAsync(res -> {
throw new RuntimeException(“error”);
})
.exceptionally(e -> {
//handle exception here
e.printStackTrace();
return null;
});
f.get();

// 执行结果处理
CompletableFuture f2 = CompletableFuture.supplyAsync(() -> “Hello”)
.thenApplyAsync(res -> res + “World”)
.thenApplyAsync(res -> {
throw new RuntimeException(“error”);
})
.handleAsync((res, err) -> {
if (err != null) {
//handle exception here

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/673215.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号