首页 > 文章列表 > Java 9中orTimeout()方法和completeOnTimeOut()方法之间的区别是什么?

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

154 2023-08-28

orTimeout()completeOnTimeOut() 方法都在 CompletableFuture 类中定义,这两个方法是Java 9 中引入。orTimeout() 方法可用于指定如果给定任务在特定时间内未完成,则程序停止执行并抛出 TimeoutException strong>而completeOnTimeOut()方法使用提供的值完成CompletableFuture。如果没有,它会在给定超时之前完成。

orTimeout() 的语法

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

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;
      CompletableFuture.supplyAsync(() -> {
         try {
            TimeUnit.SECONDS.sleep(5);
         } catch(InterruptedException e) {
            e.printStackTrace();
         }
         return a + b;
      })
      .orTimeout(4, TimeUnit.SECONDS)
      .whenComplete((result, exception) -> {
         System.out.println(result);
         if(exception != null)
            exception.printStackTrace();
      });
      TimeUnit.SECONDS.sleep(10);
   }
}

输出

25

completeOnTimeOut() 语法

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

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;
      CompletableFuture.supplyAsync(() -> {
         try {
            TimeUnit.SECONDS.sleep(5);
         } catch(InterruptedException e) {
            e.printStackTrace();
         }
         return a + b;
      })
      .completeOnTimeout(0, 4, TimeUnit.SECONDS)
      .thenAccept(result -> System.out.println(result));
      TimeUnit.SECONDS.sleep(10);
   }
}

输出

25