Java Thread How to - Call java.util.concurrent.Future.get()








Question

We would like to know how to call java.util.concurrent.Future.get().

Answer

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
/*  w w w  .  j  av  a 2s.c  o m*/
public class Main {
  public static void main(String args[]) throws Exception {
    ExecutorService executor = Executors.newCachedThreadPool();
    Future<?> future = executor.submit(()->{
        try {
          Thread.sleep(1000);
        } catch (Exception e) {
          System.out.println("Epic fail.");
        }
    });
    System.out.println("Waiting for task to finish..");
    future.get();
    System.out.println("Task finished!");
    executor.shutdown();
  }
}

The code above generates the following result.