1. class Task implements Callable<Integer> {
    2. @Override
    3. public Integer call() throws Exception {
    4. System.out.println("子线程正在计算1-100的结果");
    5. Thread.sleep(100);
    6. int sum = 0;
    7. for (int i = 0; i < 100; i++) {
    8. sum += i;
    9. }
    10. return sum;
    11. }
    12. }
    13. public class FutureTaskDemo {
    14. public static void main(String[] args) {
    15. Task task = new Task();
    16. FutureTask<Integer> integerFutureTask = new FutureTask<>(task);
    17. ExecutorService service = Executors.newCachedThreadPool();
    18. service.submit(integerFutureTask);
    19. try {
    20. System.out.println("1-100运行结果:" + integerFutureTask.get());
    21. } catch (InterruptedException e) {
    22. e.printStackTrace();
    23. } catch (ExecutionException e) {
    24. e.printStackTrace();
    25. }
    26. }
    27. }

    转成lamb

    1. public class OneFutureLambda {
    2. public static void main(String[] args) throws ExecutionException, InterruptedException {
    3. ExecutorService service = Executors.newFixedThreadPool(10);
    4. Future<Integer> future = service.submit(new Callable<Integer>() {
    5. @Override
    6. public Integer call() throws Exception {
    7. Integer sum = 0;
    8. for (int i = 1; i < 100; i++) {
    9. sum += i;
    10. }
    11. return sum;
    12. }
    13. });
    14. try {
    15. System.out.println(future.get());
    16. } catch (InterruptedException e) {
    17. e.printStackTrace();
    18. } catch (ExecutionException e) {
    19. e.printStackTrace();
    20. }
    21. service.shutdown();
    22. }
    23. }

    等价于

    1. Future<Integer> future = service.submit(() -> {
    2. Integer sum = 0;
    3. for (int i = 1; i < 100; i++) {
    4. sum += i;
    5. }
    6. return sum;
    7. });