Executing Multiple Tasks Asynchronously with CompletableFuture objects - Java Thread

Java examples for Thread:CompletableFuture

Description

Executing Multiple Tasks Asynchronously with CompletableFuture objects

Demo Code

import java.util.concurrent.CompletableFuture;

public class Main {
  public static void main(String[] args) throws Exception {
    CompletableFuture<String> tasks = performWork().thenApply(work -> {
      String newTask = work + " Second task complete!";
      System.out.println(newTask);
      return newTask;
    }).thenApply(finalTask -> finalTask + " Final Task Complete!");

    CompletableFuture<String> future = performSecondWork("test");
    while (!tasks.isDone()) {
      System.out.println(future.get());
    }//w  w  w  .  j a  v a 2s . co m
    System.out.println(tasks.get());

  }

  public static CompletableFuture<String> performWork() throws Exception{
    CompletableFuture<String> resultingWork = CompletableFuture.supplyAsync(() -> {
      String taskMessage = "First task complete!";
      try {
        Thread.sleep(1000);
      } catch (InterruptedException ex) {
        System.out.println(ex);
      }
      System.out.println(taskMessage);
      return taskMessage;
    });
    return resultingWork;

  }

  public static CompletableFuture<String> performSecondWork(String message) throws Exception{
    CompletableFuture<String> resultingWork = CompletableFuture.supplyAsync(() -> {
      String taskMessage = message + " Another task complete!";
      try {
        Thread.sleep(1000);
      } catch (Exception ex) {
        System.out.println(ex);
      }

      return taskMessage;
    });
    return resultingWork;
  }
}

Result


Related Tutorials