ホームページ  >  記事  >  Java  >  Java 9 の orTimeout() メソッドと completeOnTimeOut() メソッドの違いは何ですか?

Java 9 の orTimeout() メソッドと completeOnTimeOut() メソッドの違いは何ですか?

WBOY
WBOY転載
2023-08-27 22:53:041022ブラウズ

Java 9中orTimeout()方法和completeOnTimeOut()方法之间的区别是什么?

orTimeout() メソッドと completeOnTimeOut() メソッドは両方とも CompletableFuture クラスで定義されています。 Java 9で導入されました。 orTimeout() メソッドを使用すると、特定のタスクが特定の時間内に完了しない場合、プログラムが実行を停止し、TimeoutException Strong>while completeOnTimeOut( ) メソッドは、指定された値を使用して CompletableFuture を完了します。そうでない場合は、指定されたタイムアウト前に完了します。

orTimeout() の構文

<strong>public CompletableFuture<T> orTimeout(long timeout, TimeUnit unit)</strong>

Example

の中国語訳は次のとおりです。

Example

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
public class OrTimeoutMethodTest {
   public static void main(String args[]) throws InterruptedException {
      int a = 10;
      int b = 15;
      <strong>CompletableFuture</strong>.supplyAsync(() -> {
         try {
            TimeUnit.SECONDS.sleep(5);
         } catch(InterruptedException e) {
            e.printStackTrace();
         }
         return a + b;
      })
      .<strong>orTimeout</strong>(4, TimeUnit.SECONDS)
      .<strong>whenComplete</strong>((result, exception) -> {
         System.out.println(result);
         if(exception != null)
            exception.printStackTrace();
      });
      TimeUnit.SECONDS.sleep(10);
   }
}

Output

<strong>25
</strong>

#completeOnTimeOut() 構文

<strong>public CompletableFuture<T> completeOnTimeout(T value, long timeout, TimeUnit unit)</strong>

Example

の中国語訳は次のとおりです。

Example

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
public class CompleteOnTimeOutMethodTest {
   public static void main(String args[]) throws InterruptedException {
      int a = 10;
      int b = 15;
      <strong>CompletableFuture</strong>.supplyAsync(() -> {
         try {
            TimeUnit.SECONDS.sleep(5);
         } catch(InterruptedException e) {
            e.printStackTrace();
         }
         return a + b;
      })
      .<strong>completeOnTimeout</strong>(0, 4, TimeUnit.SECONDS)
      .<strong>thenAccept</strong>(result -> System.out.println(result));
      TimeUnit.SECONDS.sleep(10);
   }
}

Output

<strong>25</strong>

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

声明:
この記事はtutorialspoint.comで複製されています。侵害がある場合は、admin@php.cn までご連絡ください。