Java Stream How to - Submit new future thread with Lambda implementation








Question

We would like to know how to submit new future thread with Lambda implementation.

Answer

//from ww w  . ja  v a 2  s  . c om
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadLocalRandom;

public class Main {
  public static void main(String[] args) throws Exception{

    ExecutorService ex = Executors.newSingleThreadExecutor();

    Future<Integer> future =
    // This Lambda evaluated to Callable<Integer>
    ex.submit(() -> ThreadLocalRandom.current().nextInt(1, 10));

    System.out.println("Randomized value: " + future.get());

  }
}

The code above generates the following result.