Java 9 の CompletableFuture と Future の違いは何ですか?

WBOY
リリース: 2023-08-18 16:17:12
転載
976 人が閲覧しました

CompletableFuture クラスは、Java で Future インターフェイスを実装します。 CompletableFuture 明示的に完了したFutureとして使用できます。 将来 インターフェイスには多くの機能がありません。非同期計算の結果を取得するには、get() メソッドを使用する必要があります。このメソッドはブロックされるため、実行する方法はありません。 ノンブロッキング CompletableFuture クラスで複数の依存タスクを実行する クラスは、複数の依存タスクをチェーンする機能を提供できます。これらのタスクは 非同期

方法で実行されるため、次のことが可能です。現在のタスクの結果が利用可能になったときに次のタスクをトリガーするタスク チェーンを作成します。

文法

<strong>public class CompletableFuture<T> extends Object implements Future<T>, CompletionStage<T></strong>
ログイン後にコピー

中国語への翻訳:

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;
   }
}
ログイン後にコピー

出力

<strong>CompletableFutureTest End....
11</strong>
ログイン後にコピー
###

以上がJava 9 の CompletableFuture と Future の違いは何ですか?の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

ソース:tutorialspoint.com
このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
人気のチュートリアル
詳細>
最新のダウンロード
詳細>
ウェブエフェクト
公式サイト
サイト素材
フロントエンドテンプレート
私たちについて 免責事項 Sitemap
PHP中国語ウェブサイト:福祉オンライン PHP トレーニング,PHP 学習者の迅速な成長を支援します!