既orTimeout()和completeOnTimeOut()方法在定义CompletableFuture 类和这两种方法都用Java 9.引入orTimeout()方法可用于指定,如果一个给定的任务并不一定的时间周期内完成,程序停止执行并引发TimeoutException, 而completeOnTimeOut()方法使用提供的值完成CompletableFuture 。如果不是,则在给定超时之前完成。
orTimeout()
public CompletableFuture<T> orTimeout(long timeout, TimeUnit unit)
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)
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