何时使用 Java 9 中 CompletableFuture 的 delayExecutor() 方法?
Java9delayedExecutor()的CompletableFuture类中添加了该方法。CompletableFuture定义了两个重载方法delayedExecutor():第一个方法从默认的Executor对象返回一个Executor对象,CompletableFuture对象用于在延迟后执行任务,新的Executor对象可以执行任务而第二种方法也返回一个Executor对象,但它是一个Executor对象,我们在延迟后传递给这个方法,新的Executor对象也可以执行任务。
语法
public static Executor delayedExecutor(long delay, TimeUnit unit, Executor executor)public static Executor delayedExecutor(long delay, TimeUnit unit)
示例
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
public class DelayedExecutorMethodTest {
public static void main(String args[]) throws InterruptedException, ExecutionException {
CompletableFuture future = new CompletableFuture<>();
future.completeAsync(() -> {
try {
System.out.println("inside future: processing data...");
return "nhooo.com";
} catch(Throwable e) {
return "not detected";
}
}, CompletableFuture.delayedExecutor(3, TimeUnit.SECONDS))
.thenAccept(result -> System.out.println("accept: " + result));
for(int i = 1; i <= 5; i++) {
try {
Thread.sleep(1000);
} catch(InterruptedException e) {
e.printStackTrace();
}
System.out.println("在外面跑... " + i + " s");
}
}
} 输出结果在外面跑... 1 s 在外面跑... 2 s inside future: processing data... accept: nhooo.com 在外面跑... 3 s 在外面跑... 4 s 在外面跑... 5 s