Home > Java > javaTutorial > What is the difference between CompletableFuture and Future in Java 9?

What is the difference between CompletableFuture and Future in Java 9?

WBOY
Release: 2023-08-18 16:17:12
forward
1020 people have browsed it

CompletableFuture class implements the Future interface in Java. CompletableFuture Can be used as a Future that has been explicitly completed. Future The interface does not provide many functions. We need to use the get() method to obtain the results of asynchronous calculation. This method will be blocked, so there is no way to non-blocking Run multiple dependent tasks in a way, and the CompletableFuture class can provide the function of running multiple dependent tasks in a chain. These tasks run in a asynchronous

way, so we can create a Task chains that trigger the next task when the results of the current task are available.

Grammar

<strong>public class CompletableFuture<T> extends Object implements Future<T>, CompletionStage<T></strong>
Copy after login

Example

Translated into Chinese:

Example

import java.util.function.Supplier;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

public class CompletableFutureTest {
   public static void main(String args[]) throws ExecutionException, InterruptedException {
      Calculator calc = new Calculator(4, 7);
      <strong>CompletableFuture<Integer></strong> future = CompletableFuture.<strong>supplyAsync</strong>(calc);
      future.<strong>thenAccept</strong>(result -> {
         System.out.println(result);
      });
      System.out.println("CompletableFutureTest End.... ");
      Thread.sleep(10000);
   }
}

<strong>// Calculator class</strong>
class Calculator implements <strong>Supplier<Integer></strong> {
   private int x, y;
   public Calculator(int x, int y) {
      this.x = x;
      this.y = y;
   }
   <strong>@Override</strong>
   public Integer get() {
      try {
         Thread.sleep(3000);
      } catch(InterruptedException e) {
         e.printStackTrace();
      }
      return x + y;
   }
}
Copy after login

Output

<strong>CompletableFutureTest End....
11</strong>
Copy after login
###

The above is the detailed content of What is the difference between CompletableFuture and Future in Java 9?. For more information, please follow other related articles on the PHP Chinese website!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template