java中CompletableFuture方式是什么

  • 更新时间:2021-08-05 08:18:04
  • 编辑:充宏大
给寻找编程代码教程的朋友们精选了相关的编程文章,网友那秋玉根据主题投稿了本篇教程内容,涉及到java相关内容,已被944网友关注,下面的电子资料对本篇知识点有更加详尽的解释。

参考资料

正文内容

码农之家最近发表了一篇名为《java中CompletableFuture方式是什么》的Java文章,感觉写的不错,这里给大家转摘到这里,为了大家阅读方便。

java中CompletableFuture方式是什么

说明

1、JDK 8中引入了 CompletableFuture 类,实现了Future和CompletionStage接口,为异步编程提供了一些列方法,如supplyAsync、runAsync和thenApplyAsync等。

2、功能是可以让两个或者多个进行运算来产生结果。

实例

/**
 * @author mghio
 * @since 2021-08-01
 */
public class CompletableFutureDemo {
 
  public static CompletableFuture<String> doOneThing() {
    return CompletableFuture.supplyAsync(() -> {
      try {
        Thread.sleep(2000);
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
      return "doOneThing";
    });
  }
 
  public static CompletableFuture<String> doOtherThing(String parameter) {
    return CompletableFuture.supplyAsync(() -> {
      try {
        Thread.sleep(2000);
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
      return parameter + " " + "doOtherThing";
    });
  }
 
  public static void main(String[] args) throws ExecutionException, InterruptedException {
    StopWatch stopWatch = new StopWatch("CompletableFutureDemo");
    stopWatch.start();
 
    // 异步执行版本
    testCompletableFuture();
 
    stopWatch.stop();
    System.out.println(stopWatch);
  }
 
  private static void testCompletableFuture() throws InterruptedException, ExecutionException {
    // 先执行 doOneThing 任务,后执行 doOtherThing 任务
    CompletableFuture<String> resultFuture = doOneThing().thenCompose(CompletableFutureDemo::doOtherThing);
 
    // 获取任务结果
    String doOneThingResult = resultFuture.get();
 
    // 获取执行结果
    System.out.println("DoOneThing and DoOtherThing execute finished. result = " + doOneThingResult);
  }
 
}

以上就是java中CompletableFuture方式的介绍,希望对大家有所帮助。

本文转载于segmentfault,如有侵犯联系作者修改。

相关教程

  • JAVA通过HttpURLConnection 上传和下载文件的方法

    这篇文章主要介绍了JAVA通过HttpURLConnection 上传和下载文件的方法,非常具有实用价值,需要的朋友可以参考下

    发布时间:2019-08-28

  • 零基础Java就业班难不难,基础知识下载

      Java是现在大型软件项目中的主角,市场用人需求量大。大家都知道21世纪进入信息时代,信息科技给人类的生产和生活方式带来了深刻的变革,信息产业已成为推动国家经济发展的主导产业之一,为此,从就业前景,发展方向等多方面来看,学Java编程无疑是最佳选择,具备了显著优势和广阔前景。

    发布时间:2021-06-06

用户留言