thenRun()
is an instance method of the CompletableFuture
. It executes a runnable once the CompletableFuture
is in the completed stage. It has no access to the result of the CompletableFuture
to which it is attached.
The thenRun
method is defined in the CompletableFuture
class, which is defined in the java.util.concurrent
package. To import the CompletableFuture
class, we use the following import statement:
import java.util.concurrent.CompletableFuture;
public CompletableFuture<Void> thenRun(Runnable action)
Runnable action
: It is the runnable action to be run.This method returns a new CompletableFuture
.
import java.util.concurrent.*;public class Main {static void sleep(int millis){try {Thread.sleep(millis);} catch (InterruptedException e) {e.printStackTrace();}}static void executionThread(){System.out.println("Thread execution - " + Thread.currentThread().getName());}public static void main(String[] args){CompletableFuture<String> completableFuture1 = CompletableFuture.supplyAsync(() -> {sleep(1000);String stringToPrint = "Educative";System.out.println("----\nsupplyAsync first future - " + stringToPrint);executionThread();return stringToPrint;});Runnable runnable = () -> System.out.println("Runnable executed");completableFuture1.thenAccept(System.out::println).thenRun(runnable);sleep(2000);}}
sleep()
, which makes the current thread sleep for the given amount of milliseconds.executionThread()
, which prints the current thread of execution.completableFuture1
using the supplyAsyc()
method. We do this by passing a supplier that sleeps for 1 second, invokes the executionThread()
method, and returns a string value.completableFuture1
.completableFuture1
is complete, we print the value returned by the future using the thenAccept()
method. Then, the runnable is executed.