何时在 Java 9 中使用 CompletableFuture 的 delayedExecutor() 方法?


delayedExecutor()方法已添加到了 Java 9 中的CompletableFuture类。CompletableFuture定义了delayedExecutor()的两个重载方法:第一个方法从默认Executor对象返回一个 Executor 对象,该CompletableFuture对象在延迟后使用该对象执行任务,并且new Executor对象可以执行任务,而第二个方法也返回一个 Executor 对象,但这是一个Executor对象,我们在延迟后将该对象传递到此方法中,并且new 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<String> future = new CompletableFuture<>();
      future.completeAsync(() -> {
         try {
            System.out.println("inside future: processing data...");
            return "tutorialspoint.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("running outside... " + i + " s");
      }
   }
}

输出

running outside... 1 s
running outside... 2 s
inside future: processing data...
accept: tutorialspoint.com
running outside... 3 s
running outside... 4 s
running outside... 5 s

更新于: 09-03-2020

3K+ 浏览

职业够用

完成课程然后获取认证

开始
广告