Computer >> Máy Tính >  >> Lập trình >> Java

Sự khác biệt giữa các phương thức orTimeout () và completeOnTimeOut () trong Java 9?


Cả orTimeout () completeOnTimeOut () các phương thức được xác định trong CompletableFuture lớp và hai phương thức này được giới thiệu trong Java 9. orTimeout () phương thức có thể được sử dụng để chỉ định rằng nếu một nhiệm vụ nhất định không hoàn thành trong một khoảng thời gian nhất định, chương trình sẽ dừng thực thi và ném TimeoutException trong khi completeOnTimeOut () phương thức hoàn thành CompletableFuture với giá trị được cung cấp. Nếu không, nó sẽ hoàn tất trước thời gian chờ nhất định.

Cú pháp cho orTimeout ()

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

Ví dụ

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

Đầu ra

25


Cú pháp cho completeOnTimeOut ()

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

Ví dụ

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

Đầu ra

25