runAsync()
is a CompletableFuture
which is used to execute a runnable asynchronously in a pool of threads.
The runAsync
method is defined in the CompletableFuture
class. The CompletableFuture
class is defined in the java.util.concurrent
package. To import the CompletableFuture
class check the following import statement.
import java.util.concurrent.CompletableFuture;
runAsync(Runnable runnable)
This method considers the passed Runnable
implementation as a task that will be completed asynchronously. By default, the task will be executed asynchronously in ForkJoinPool.commonPool()
and the method returns a new CompletableFuture
with no value.
public static CompletableFuture<Void> runAsync(Runnable runnable)
Runnable runnable
: The task to execute.This method returns a new CompletableFuture
.
import java.util.concurrent.*;public class Main {private static CompletableFuture<Void> createFuture(){Runnable runnable = () -> {sleep(1000);System.out.println("Hello Educative");System.out.println("Current Execution thread where the supplier is executed - " + Thread.currentThread().getName());};return CompletableFuture.runAsync(runnable);}private static void sleep(int millis){try {Thread.sleep(millis);} catch (InterruptedException e) {e.printStackTrace();}}public static void main(String[] args) throws ExecutionException, InterruptedException {createFuture().get();sleep(3000);System.out.println("Completed Processing");}}
createFuture()
which submits the runnable
to the ForkJoinPool.commonPool()
and returns a CompletableFuture
.sleep()
that makes the current thread sleep for the given amount of milliseconds.CompletableFuture
by invoking the createFuture
method. Using the get()
method, we wait for the future to complete the execution.Completed Processing
to the console.