首頁  >  文章  >  Java  >  Java 9中orTimeout()方法和completeOnTimeOut()方法之間的差異是什麼?

Java 9中orTimeout()方法和completeOnTimeOut()方法之間的差異是什麼?

WBOY
WBOY轉載
2023-08-27 22:53:041023瀏覽

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

orTimeout()completeOnTimeOut() 方法都在CompletableFuture 類別中定義,這兩個方法是Java 9 中引入。 orTimeout() 方法可用來指定如果給定任務在特定時間內未完成,則程式停止執行並拋出TimeoutException strong>而completeOnTimeOut()方法使用提供的值完成CompletableFuture。如果沒有,它會在給定超時之前完成。

orTimeout() 的語法

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

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);
   }
}

輸出

<strong>25
</strong>

#completeOnTimeOut() 語法

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

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);
   }
}

輸出

<strong>25</strong>

以上是Java 9中orTimeout()方法和completeOnTimeOut()方法之間的差異是什麼?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:tutorialspoint.com。如有侵權,請聯絡admin@php.cn刪除