Home  >  Article  >  Java  >  Methods and examples of using CompletableFuture in Java

Methods and examples of using CompletableFuture in Java

WBOY
WBOYforward
2023-04-23 08:10:061220browse

Explanation

1. The CompletableFuture class was introduced in JDK 8 and implemented the Future and CompletionStage interfaces.

Provides a series of methods for asynchronous programming, such as supplyAsync , runAsync and thenApplyAsync, etc.

2. The function allows two or more to perform operations to produce results.

Example

/**
 * @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);
  }
 
}

The above is the detailed content of Methods and examples of using CompletableFuture in Java. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete