• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

Java8 CompletableFuture 异步执行操作

java 搞代码 4年前 (2022-01-05) 35次浏览 已收录 0个评论
文章目录[隐藏]

CompletableFuture是java8提供的基于异步操作的封装,日常开发中经常会用到,接下来通过本文给大家介绍Java8 CompletableFuture 异步执行操作,感兴趣的朋友一起看看吧

1.简介

CompletableFuture 是 JDK8来源gao@daima#com搞(%代@#码@网 提供的一个异步执行工具。

示例1:

 public static void main(String[] args) throws ExecutionException, InterruptedException { CompletableFuture future = CompletableFuture.runAsync(() -> { for (int i = 0; i <3; i++) { System.out.println(i); try { Thread.sleep(1000L); } catch (InterruptedException ignored) { } } System.out.println("Future Finished."); }); System.out.println("Main Thread Finished."); future.get(); }

输出结果1:

2.异步执行

CompletableFuture 提供了两个方法用于异步执行:

CompletableFuture.runAsync,没有返回值

CompletableFuture.supplyAsync,有返回值

示例:

 public static void main(String[] args) throws ExecutionException, InterruptedException { // runAsync 没有返回值 CompletableFuture future1 = CompletableFuture.runAsync(() -> System.out.println("future1 executed.")); // supplyAsync 有返回值 CompletableFuture future2 = CompletableFuture.supplyAsync(() -> { System.out.println("future2 executed."); return "result"; }); System.out.println("future1.get(): " + future1.get()); System.out.println("future2.get(): " + future2.get()); }

输出结果:

3.守护线程

CompletableFuture返回的Future默认为守护线程,如果不调用get()获取结果,主线程结束后会自动结束。主要有以下4种情景:

  • 情景1: 执行时间 > 主线程时间,异步线程会执行
  • 情景2: 执行时间 > 主线程,是守护线程,会被杀死,异步线程不会执行
  • 情景3: 执行时间 > 主线程,但是不是守护线程,不会被杀死,异步线程会执行
  • 情景4: ExecutorService.submit(),默认不是守护线程,不会被杀死,异步线程会执行

示例:

 public static void main(String[] args) { ExecutorService executorService = Executors.newFixedThreadPool(2); // 1.执行时间 <主线程,会打印 CompletableFuture future1 = CompletableFuture.runAsync(() -> System.out.println("Thread1 是否为守护线程 : " + Thread.currentThread().isDaemon())); // 2.执行时间 > 主线程,是守护线程,会被杀死,不会打印 CompletableFuture.runAsync(() -> { try { Thread.sleep(3000L); System.out.println("Thread2 是否为守护线程 : " + Thread.currentThread().isDaemon()); } catch (InterruptedException e) { e.printStackTrace(); }}); // 3.执行时间 > 主线程,但是不是守护线程,不会被杀死,会打印 CompletableFuture.runAsync(() -> { try { Thread.sleep(1000L); System.out.println("Thread3 等待1秒"); System.out.println("Thread3 是否为守护线程 : " + Thread.currentThread().isDaemon()); } catch (InterruptedException e) { e.printStackTrace(); }}, executorService); // 4.ExecutorService.submit(),默认不是守护线程,不会被杀死,会打印。 executorService.submit(() -> { try { Thread.sleep(2000L); System.out.println("Thread4 等待2秒"); System.out.println("Thread4 是否为守护线程 : " + Thread.currentThread().isDaemon()); } catch (InterruptedException e) { e.printStackTrace(); }}); // 主线程执行完毕 System.out.println("Main Thread Finished."); executorService.shutdown(); }

输出结果2:

4.处理执行结果

CompletableFuture还封装了很多处理执行结果操作。操作太多,列举比较常用的几种:

thenAccept(): 对结果进行使用;

thenApply(): 对结果进行转换;

exceptionally(): 对异常进行处理;

whenComplete(): 相当于 thenAccept() + thenApply() + exceptionally().

示例:

 public static void main(String[] args) { // thenAccept对结果进行使用 System.out.println("------------------------------"); CompletableFuture.supplyAsync(() -> "Thread1 Finished.").thenAccept(System.out::println); // thenApply对结果进行转换 System.out.println("------------------------------"); CompletableFuture.supplyAsync(() -> "Thread2 Finished.") .thenApply(s -> s + " + thenApply()") .thenAccept(System.out::println); // exceptionally对异常进行处理 System.out.println("------------------------------"); CompletableFuture.supplyAsync(() -> {throw new RuntimeException("Thread3 Failed.");}) .exceptionally(Throwable::toString).thenAccept(System.out::println); // 主线程执行完毕 System.out.println("------------------------------"); System.out.println("Main Thread Finished."); }

输出结果:

whenComplete() 示例:

 public static void main(String[] args) throws ExecutionException, InterruptedException { // thenAccept对结果进行使用 System.out.println("------------------------------"); CompletableFuture future = CompletableFuture.supplyAsync(() -> "Thread1 Finished.").whenComplete(new BiConsumer() { @Override public void accept(String s, Throwable throwable) { System.out.println("result: " + s); System.out.println("throwable: " + throwable); } }); // exceptionally对异常进行处理 System.out.println("------------------------------"); CompletableFuture.supplyAsync(() -> { throw new RuntimeException("Thread3 Failed."); }).whenComplete(new BiConsumer() { @Override public void accept(Object s, Throwable throwable) { System.out.println("result: " + s); System.out.println("throwable: " + throwable); } }); System.out.println("------------------------------"); System.out.println("future.get(): " + future.get()); // 主线程执行完毕 System.out.println("------------------------------"); System.out.println("Main Thread Finished."); }

输出结果:

整理完毕,完结撒花~

以上就是Java8 CompletableFuture 异步执行的详细内容,更多关于Java8 CompletableFuture 异步执行的资料请关注gaodaima搞代码网其它相关文章!

以上就是Java8 CompletableFuture 异步执行操作的详细内容,更多请关注gaodaima搞代码网其它相关文章!


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:Java8 CompletableFuture 异步执行操作

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址