This method was introduced from Java 9.
Here we have two overload methods delayedExecutor(), the first method has the following syntax:
1 |
static Executor delayedExecutor(long delay, TimeUnit unit) |
This method returns an Executor object from the default Executor object that the CompletableFuture object uses to execute the task, after the delay. And this new Executor object will do task execution.
The second is:
1 |
static Executor delayedExecutor(long delay, TimeUnit unit, Executor executor) |
This method also returns an Executor object but is an Executor object that we pass into this method, after the delay. And this new Executor object will also do task execution.
For example, I want to calculate the sum of two numbers and for some conditions, I want it to happen after 2 seconds, my code will look like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
package com.huongdanjava.javaexample; import java.util.concurrent.CompletableFuture; import java.util.concurrent.TimeUnit; public class Example { public static void main(String[] args) throws InterruptedException { int a = 2; int b = 5; CompletableFuture.supplyAsync(() -> a + b, CompletableFuture.delayedExecutor(2, TimeUnit.SECONDS)) .thenAccept(result -> System.out.println(result)); TimeUnit.SECONDS.sleep(10); } } |
When running the above example, you will see after 2s, the results will appear: